javascript

exercises

exercises.js
/**
 * ============================================
 * 2.1 Variables - Exercises
 * ============================================
 *
 * Test your understanding of var, let, and const.
 * Solutions are at the bottom.
 */

// ============================================
// EXERCISE 1: Basic Declaration
// ============================================
// Declare and initialize:
// a) A variable for a user's name (cannot be reassigned)
// b) A variable for a counter that starts at 0 (will be changed)
// c) A constant for the maximum score (100)

// YOUR CODE HERE:

// ============================================
// EXERCISE 2: Predict the Output
// ============================================
// For each snippet, predict what will be logged (or if it will error)

// 2a)
console.log(a);
var a = 10;
// Prediction:

// 2b)
// console.log(b);
// let b = 20;
// Prediction (if uncommented):

// 2c)
const obj = { x: 1 };
obj.x = 2;
console.log(obj.x);
// Prediction:

// ============================================
// EXERCISE 3: Scope Analysis
// ============================================
// What will each console.log output? Write your prediction.

function scopeExercise() {
  var x = 1;
  let y = 2;
  const z = 3;

  if (true) {
    var x = 10;
    let y = 20;
    const z = 30;
    console.log('Inside if - x:', x); // Prediction:
    console.log('Inside if - y:', y); // Prediction:
    console.log('Inside if - z:', z); // Prediction:
  }

  console.log('Outside if - x:', x); // Prediction:
  console.log('Outside if - y:', y); // Prediction:
  console.log('Outside if - z:', z); // Prediction:
}
// Uncomment to test:
// scopeExercise();

// ============================================
// EXERCISE 4: Fix the Bug
// ============================================
// This code has a bug. Fix it using let instead of var.

/*
function createFunctions() {
    var funcs = [];
    for (var i = 0; i < 5; i++) {
        funcs.push(function() {
            return i;
        });
    }
    return funcs;
}

var functions = createFunctions();
console.log(functions[0]()); // Should return 0, but returns 5
console.log(functions[1]()); // Should return 1, but returns 5
console.log(functions[2]()); // Should return 2, but returns 5
*/

// YOUR FIXED CODE HERE:

// ============================================
// EXERCISE 5: const with Objects
// ============================================
// Without causing an error, modify the person object:
// a) Change the age to 31
// b) Add a new property 'city' with value 'New York'
// c) Try to reassign person to a new object (comment out if it errors)

const person = { name: 'Alice', age: 30 };

// YOUR CODE HERE:

// ============================================
// EXERCISE 6: const with Arrays
// ============================================
// Perform these operations on the colors array:
// a) Add "yellow" to the end
// b) Change "red" to "crimson"
// c) Remove the last element
// d) Try to reassign colors to a new array (comment out if it errors)

const colors = ['red', 'green', 'blue'];

// YOUR CODE HERE:

// ============================================
// EXERCISE 7: TDZ Challenge
// ============================================
// Explain why this code throws an error:

/*
function tdzChallenge() {
    console.log(value);  // What happens here?
    let value = 42;
}
*/

// YOUR EXPLANATION:

// ============================================
// EXERCISE 8: Choose the Right Declaration
// ============================================
// For each scenario, choose var, let, or const and explain why:

// 8a) Store API endpoint URL
// Your choice and code:

// 8b) Loop counter variable
// Your choice and code:

// 8c) User's current shopping cart (array that will be modified)
// Your choice and code:

// 8d) Mathematical constant (e.g., speed of light)
// Your choice and code:

// 8e) Current page in pagination (changes when user navigates)
// Your choice and code:

// ============================================
// EXERCISE 9: Hoisting Quiz
// ============================================
// Rewrite how JavaScript interprets this code after hoisting:

/*
console.log(x);
console.log(y);
var x = 5;
let y = 10;
console.log(x);
console.log(y);
*/

// JavaScript interprets it as:
// YOUR ANSWER:

// ============================================
// EXERCISE 10: Redeclaration Test
// ============================================
// Which of these will cause an error? Mark with ❌ or ✓

// 10a)
var test1 = 1;
var test1 = 2;
// Error?

// 10b)
let test2 = 1;
// let test2 = 2;
// Error if uncommented?

// 10c)
let test3 = 1;
if (true) {
  let test3 = 2;
}
// Error?

// 10d)
const test4 = 1;
// const test4 = 2;
// Error if uncommented?

// ============================================
// EXERCISE 11: Block Scope Practice
// ============================================
// Create a function that demonstrates block scope
// It should:
// 1. Declare a variable 'outer' with value "I'm outer" outside any block
// 2. Create an if block that declares 'inner' with value "I'm inner"
// 3. Inside the if, log both outer and inner
// 4. Outside the if, log outer and try to log inner (handle the error)

// YOUR CODE HERE:

// ============================================
// EXERCISE 12: Variable Swap
// ============================================
// Swap the values of a and b using:
// a) A temporary variable
// b) Destructuring (no temp variable)

let swapA = 10;
let swapB = 20;

// Method a) With temp variable:

// Method b) With destructuring:

// ============================================
// EXERCISE 13: Real-World Scenario
// ============================================
// Create a simple counter module with:
// - A private count variable (using closure)
// - An increment function
// - A decrement function
// - A getCount function
// Use appropriate variable declarations (const/let)

// YOUR CODE HERE:

// ============================================
// EXERCISE 14: Global Scope
// ============================================
// In a browser, what's the difference between:
// var globalVar = "test";
// let globalLet = "test";
// When accessed via window object?

// YOUR EXPLANATION:

// ============================================
// EXERCISE 15: Debugging Challenge
// ============================================
// Find and fix all the bugs in this code:

/*
function calculateTotal(items) {
    const total;
    
    for (var i = 0; i <= items.length; i++) {
        total = total + items[i].price;
    }
    
    let discount = 0.1;
    let discount = 0.2;
    
    return total * (1 - discount);
}
*/

// YOUR FIXED VERSION:

// ============================================
// ============================================
//              SOLUTIONS
// ============================================
// ============================================

/*

// SOLUTION 1
const userName = "John";
let counter = 0;
const MAX_SCORE = 100;


// SOLUTION 2
// 2a) undefined (var is hoisted)
// 2b) ReferenceError (let is in TDZ)
// 2c) 2 (const allows mutation of object properties)


// SOLUTION 3
// Inside if - x: 10
// Inside if - y: 20
// Inside if - z: 30
// Outside if - x: 10 (var is function scoped, gets overwritten)
// Outside if - y: 2 (let is block scoped, outer y unchanged)
// Outside if - z: 3 (const is block scoped, outer z unchanged)


// SOLUTION 4
function createFunctions() {
    const funcs = [];
    for (let i = 0; i < 5; i++) {  // Changed var to let
        funcs.push(function() {
            return i;
        });
    }
    return funcs;
}

const functions = createFunctions();
console.log(functions[0]()); // 0
console.log(functions[1]()); // 1
console.log(functions[2]()); // 2


// SOLUTION 5
const person = { name: "Alice", age: 30 };
person.age = 31;           // a) Change age
person.city = "New York";  // b) Add city
// person = {};            // c) This errors! Cannot reassign const


// SOLUTION 6
const colors = ["red", "green", "blue"];
colors.push("yellow");     // a) Add yellow
colors[0] = "crimson";     // b) Change red to crimson
colors.pop();              // c) Remove last element
// colors = [];            // d) This errors! Cannot reassign const


// SOLUTION 7
// The error occurs because of the Temporal Dead Zone (TDZ).
// When let is used, the variable is hoisted but not initialized.
// Accessing it before the declaration line throws a ReferenceError.
// The TDZ exists from the start of the block until the let declaration.


// SOLUTION 8
// 8a) const API_URL = "https://api.example.com"; // Won't change
// 8b) for (let i = 0; i < 10; i++) { } // Needs reassignment
// 8c) const cart = []; // Reference won't change, contents will
// 8d) const SPEED_OF_LIGHT = 299792458; // Constant value
// 8e) let currentPage = 1; // Will be reassigned


// SOLUTION 9
// var x;                   // Declaration hoisted
// console.log(x);          // undefined
// console.log(y);          // ReferenceError! (let is in TDZ)
// x = 5;                   // Assignment stays in place
// let y = 10;              // let declaration
// console.log(x);          // 5
// console.log(y);          // Never reached due to error above


// SOLUTION 10
// 10a) ✓ No error - var allows redeclaration
// 10b) ❌ Error - let doesn't allow redeclaration in same scope
// 10c) ✓ No error - different scopes, both are valid
// 10d) ❌ Error - const doesn't allow redeclaration


// SOLUTION 11
function blockScopeDemo() {
    let outer = "I'm outer";
    
    if (true) {
        let inner = "I'm inner";
        console.log(outer);  // "I'm outer"
        console.log(inner);  // "I'm inner"
    }
    
    console.log(outer);      // "I'm outer"
    try {
        console.log(inner);  // ReferenceError
    } catch (e) {
        console.log("Error: inner is not accessible outside the block");
    }
}


// SOLUTION 12
let swapA = 10;
let swapB = 20;

// Method a) With temp variable:
let temp = swapA;
swapA = swapB;
swapB = temp;

// Method b) With destructuring:
[swapA, swapB] = [swapB, swapA];


// SOLUTION 13
const createCounter = () => {
    let count = 0;  // Private via closure
    
    return {
        increment: () => ++count,
        decrement: () => --count,
        getCount: () => count
    };
};

const counter = createCounter();
console.log(counter.getCount()); // 0
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1


// SOLUTION 14
// var globalVar creates a property on window: window.globalVar === "test"
// let globalLet does NOT create a property: window.globalLet === undefined
// Both are accessible as global variables, but only var attaches to window object.


// SOLUTION 15
function calculateTotal(items) {
    let total = 0;  // Changed const to let, added initialization
    
    for (let i = 0; i < items.length; i++) {  // Changed var to let, < instead of <=
        total = total + items[i].price;
    }
    
    const discount = 0.2;  // Removed duplicate declaration, use const
    
    return total * (1 - discount);
}

*/
Exercises - JavaScript Tutorial | DeepML