javascript
exercises
exercises.js⚡javascript
/**
* ============================================
* 1.2 Basic Syntax - Exercises
* ============================================
*
* Complete these exercises to test your understanding.
* Solutions are at the bottom.
*/
// ============================================
// EXERCISE 1: Expression or Statement?
// ============================================
// For each item below, write "expression" or "statement" in the comment
// 1a) 5 + 3 // Your answer:
// 1b) let x = 10; // Your answer:
// 1c) if (true) {} // Your answer:
// 1d) x > 5 ? "yes" : "no" // Your answer:
// 1e) for (let i=0; i<5; i++) {} // Your answer:
// 1f) console.log("hi") // Your answer:
// 1g) "Hello" + " World" // Your answer:
// 1h) function greet() {} // Your answer:
// ============================================
// EXERCISE 2: Valid or Invalid Identifiers?
// ============================================
// Mark each identifier as "valid" or "invalid" with reason
// 2a) firstName // Your answer:
// 2b) 1stPlace // Your answer:
// 2c) _private // Your answer:
// 2d) my-variable // Your answer:
// 2e) $element // Your answer:
// 2f) class // Your answer:
// 2g) myClass // Your answer:
// 2h) user name // Your answer:
// ============================================
// EXERCISE 3: Fix the Naming
// ============================================
// Rename these variables following JavaScript conventions
// 3a) Rename to follow variable conventions
let USERAGE = 25; // Rename this
let user_first_name = "Jo"; // Rename this
// 3b) Rename to follow constant conventions
let maxsize = 100; // Rename this
let apiUrl = "http://..."; // Rename this
// 3c) Rename to follow boolean conventions
let active = true; // Rename this
let permission = false; // Rename this
// YOUR CODE HERE:
// ============================================
// EXERCISE 4: Semicolon Issues
// ============================================
// This function has a bug due to ASI. Fix it.
function getBrokenObject() {
return
{
message: "Hello",
count: 42
};
}
// Test: console.log(getBrokenObject()); // Should return object, not undefined
// YOUR FIXED VERSION HERE:
// ============================================
// EXERCISE 5: Expression Power
// ============================================
// Rewrite this if/else as a ternary expression
let temperature = 30;
let weatherStatement;
if (temperature > 25) {
weatherStatement = "It's hot";
} else {
weatherStatement = "It's cool";
}
// YOUR TERNARY VERSION HERE:
// let weatherTernary =
// ============================================
// EXERCISE 6: Nested Ternary
// ============================================
// Convert this if/else chain to nested ternary
let score = 85;
let letterGrade;
if (score >= 90) {
letterGrade = "A";
} else if (score >= 80) {
letterGrade = "B";
} else if (score >= 70) {
letterGrade = "C";
} else {
letterGrade = "F";
}
// YOUR NESTED TERNARY HERE:
// let gradeTernary =
// ============================================
// EXERCISE 7: Write Good Comments
// ============================================
// The following code has bad/obvious comments.
// Rewrite them to be useful (explain WHY, not WHAT)
// Bad comments - rewrite these
let i = 0; // Set i to 0
i++; // Increment i
let result = 5 + 3; // Add 5 and 3
let isTrue = true; // Set isTrue to true
// YOUR BETTER COMMENTED VERSION HERE:
// ============================================
// EXERCISE 8: JSDoc Documentation
// ============================================
// Write a JSDoc comment for this function
function calculateDiscount(originalPrice, discountPercent) {
const discount = originalPrice * (discountPercent / 100);
return originalPrice - discount;
}
// YOUR JSDOC HERE (write it above the function):
// ============================================
// EXERCISE 9: Expression Statements
// ============================================
// Which of these are valid expression statements?
// Uncomment the valid ones and explain why invalid ones don't work
// let x = 5;
// 5 + 3;
// if (true) { };
// console.log("hi");
// function() {};
// (function() {});
// x = 10;
// ============================================
// EXERCISE 10: Whitespace in Strings
// ============================================
// Create strings that will print exactly as shown:
// Expected output 1: "Hello World" (4 spaces between)
// YOUR CODE:
// Expected output 2:
// "Line 1
// Line 2 with indent"
// YOUR CODE:
// Expected output 3: "She said: "Hello""
// YOUR CODE:
// ============================================
// EXERCISE 11: Variable Declaration Analysis
// ============================================
// Identify what's wrong with each declaration
// let 123start = "test"; // Problem:
// let my-var = 10; // Problem:
// let const = 5; // Problem:
// let my var = "hi"; // Problem:
// let #tag = "hash"; // Problem:
// ============================================
// EXERCISE 12: Fix ASI Dangers
// ============================================
// These code snippets have ASI-related bugs. Fix them.
// Bug 1: Should return [1, 2, 3] but returns undefined
function getArray() {
return
[1, 2, 3];
}
// Bug 2: This will cause an error
let value = 10
[1, 2, 3].forEach(n => console.log(n))
// YOUR FIXES HERE:
// ============================================
// EXERCISE 13: Code Organization
// ============================================
// Organize this messy code with proper whitespace, comments, and sections
let firstname="John";let lastname="Doe";let age=30;function getfullname(){return firstname+" "+lastname;}function isadult(){return age>=18;}let fullname=getfullname();let adult=isadult();console.log(fullname);console.log(adult);
// YOUR ORGANIZED VERSION HERE:
// ============================================
// EXERCISE 14: Naming Convention Quiz
// ============================================
// Give proper names for the following scenarios:
// 14a) A variable storing whether user is logged in
// Your name:
// 14b) A constant for maximum password length
// Your name:
// 14c) A function that gets user data from server
// Your name:
// 14d) A class representing a shopping cart item
// Your name:
// 14e) A private variable for internal counter
// Your name:
// ============================================
// EXERCISE 15: Complex Expression
// ============================================
// Create a single expression that:
// - Takes two numbers (use variables)
// - Returns "sum is even" if their sum is even
// - Returns "sum is odd" if their sum is odd
let num1 = 7;
let num2 = 5;
// YOUR SINGLE EXPRESSION HERE:
// let result =
// ============================================
// ============================================
// SOLUTIONS
// ============================================
// ============================================
/*
// SOLUTION 1: Expression or Statement?
// 1a) expression - produces value 8
// 1b) statement - declares a variable
// 1c) statement - performs an action
// 1d) expression - produces "yes" or "no"
// 1e) statement - loop is a statement
// 1f) expression - function call returns undefined
// 1g) expression - produces "Hello World"
// 1h) statement - function declaration
// SOLUTION 2: Valid or Invalid Identifiers?
// 2a) valid - follows camelCase
// 2b) invalid - starts with number
// 2c) valid - underscore is allowed at start
// 2d) invalid - hyphens not allowed
// 2e) valid - $ is allowed at start
// 2f) invalid - reserved keyword
// 2g) valid - myClass is not a reserved word
// 2h) invalid - spaces not allowed
// SOLUTION 3: Fix the Naming
let userAge = 25;
let userFirstName = "Jo";
const MAX_SIZE = 100;
const API_URL = "http://...";
let isActive = true;
let hasPermission = false;
// SOLUTION 4: Semicolon Issues
function getFixedObject() {
return {
message: "Hello",
count: 42
};
}
// SOLUTION 5: Expression Power
let weatherTernary = temperature > 25 ? "It's hot" : "It's cool";
// SOLUTION 6: Nested Ternary
let gradeTernary = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "F";
// SOLUTION 7: Write Good Comments
// Loop counter for tracking pagination offset
let i = 0;
i++; // Move to next page
// Price before tax is applied
let result = 5 + 3;
// Feature flag for new dashboard (enable after QA approval)
let isTrue = true;
// SOLUTION 8: JSDoc Documentation
/**
* Calculates the discounted price of an item.
*
* @param {number} originalPrice - The original price before discount
* @param {number} discountPercent - The discount percentage (0-100)
* @returns {number} The final price after applying the discount
* @example
* // Returns 80 (20% off of 100)
* calculateDiscount(100, 20);
*/
// SOLUTION 9: Expression Statements
// let x = 5; - Valid (declaration statement)
// 5 + 3; - Valid expression statement (but useless)
// if (true) { }; - Not an expression statement
// console.log("hi"); - Valid expression statement
// function() {}; - Invalid (syntax error, needs name or variable)
// (function() {}); - Valid expression (IIFE ready)
// x = 10; - Valid expression statement
// SOLUTION 10: Whitespace in Strings
let str1 = "Hello World";
let str2 = "Line 1\n Line 2 with indent";
let str3 = 'She said: "Hello"';
// or
let str3alt = "She said: \"Hello\"";
// SOLUTION 11: Variable Declaration Analysis
// let 123start = "test"; // Problem: Can't start with number
// let my-var = 10; // Problem: Hyphen not allowed
// let const = 5; // Problem: Reserved keyword
// let my var = "hi"; // Problem: Space not allowed
// let #tag = "hash"; // Problem: # not allowed (except for private class fields)
// SOLUTION 12: Fix ASI Dangers
// Bug 1 Fix:
function getArrayFixed() {
return [1, 2, 3];
}
// Bug 2 Fix:
let value = 10;
[1, 2, 3].forEach(n => console.log(n));
// SOLUTION 13: Code Organization
// ==========================================
// USER DATA
// ==========================================
let firstName = "John";
let lastName = "Doe";
let age = 30;
// ==========================================
// UTILITY FUNCTIONS
// ==========================================
/**
* Returns the user's full name
*/
function getFullName() {
return firstName + " " + lastName;
}
/**
* Checks if user is an adult (18+)
*/
function isAdult() {
return age >= 18;
}
// ==========================================
// MAIN EXECUTION
// ==========================================
let fullName = getFullName();
let adult = isAdult();
console.log(fullName);
console.log(adult);
// SOLUTION 14: Naming Convention Quiz
// 14a) isLoggedIn or isUserLoggedIn
// 14b) MAX_PASSWORD_LENGTH
// 14c) fetchUserData or getUserData
// 14d) CartItem or ShoppingCartItem
// 14e) _counter or #counter
// SOLUTION 15: Complex Expression
let result = (num1 + num2) % 2 === 0 ? "sum is even" : "sum is odd";
*/