Month 1, Week 4

JavaScript - The Language Core (Part 2)

Repetition, Reusability, and Collections

Module 0: Week 3 Review

Solidifying Our Logical Foundation

Recap: The Brain of a Program

In Week 3, we learned that a program's "intelligence" comes from its ability to make decisions. This is Control Flow.

Every decision boils down to a single question that results in true or false (a **Boolean Expression**).


                        const userAge = 25;
                        const hasAccount = true;
                        
                        // A complex boolean expression
                        const canAccessContent = hasAccount && (userAge >= 18); // true
                    

Deep Dive: Truthy & Falsy

A condition (if (...)) doesn't strictly need truetrue` to pass. It only needs a "truthy" value.

JavaScript has only **6 Falsy Values**. Memorize them.

  • false
  • 0
  • "" or '' (an empty string)
  • null
  • undefined
  • NaN (Not-a-Number)

Everything else is Truthy! (e.g., 'hello', 52, [], {}, 'false')

Deep Dive: switch Statement

Use a switch statement as a clean alternative to a long if/else if chain when checking a **single variable** against multiple **specific, exact values**.


                        const httpStatusCode = 404;
                        let message;

                        switch (httpStatusCode) {
                            case 200:
                                message = 'OK';
                                break; // The 'break' is crucial! It exits the switch.
                            case 403:
                                message = 'Forbidden';
                                break;
                            case 404:
                                message = 'Not Found';
                                break;
                            default: // Runs if no other case matches.
                                message = 'Unknown Status Code';
                        }
                        // message is now 'Not Found'
                    

Module 1: Loops

Teaching the Computer to Repeat Itself

The for Loop

The classic loop, used when you know **how many times** you want to repeat.

Anatomy: for (initialization; condition; final-expression)


                        for (let i = 0; i < 5; i++) {
                            console.log(`This is iteration number ${i + 1}`);
                        }
                    
  1. Initialization: let i = 0; - Runs **once** at the very beginning.
  2. Condition: i < 5; - Checked **before** each iteration. If false, the loop stops.
  3. Final Expression: i++ - Runs **after** each iteration.

The while Loop

Used when you want to loop as long as a condition is true, but you **don't know exactly how many iterations** it will take.


                        let diceRoll = 0;
                        let attempts = 0;
                        
                        while (diceRoll !== 6) {
                            diceRoll = Math.floor(Math.random() * 6) + 1;
                            attempts++;
                            console.log(`Attempt #${attempts}: Rolled a ${diceRoll}`);
                        }
                        console.log(`Success! It took ${attempts} attempts to roll a 6.`);
                    

Warning: Ensure the condition will eventually become false to avoid an **infinite loop**!

Module 2: Functions

The Art of Reusability

Anatomy of a Function


                        // 1. Declaration using the 'function' keyword
                        function greet(name) { // 'name' is a parameter
                            // 3. The function body (the logic)
                            const message = `Hello, ${name}!`;
                            return message; // 4. The return statement
                        }

                        // 2. Calling the function
                        const greetingForAlex = greet('Alex'); // 'Alex' is an argument
                        console.log(greetingForAlex); // "Hello, Alex!"
                    
  • Parameters: Placeholder variables in the function definition.
  • Arguments: The actual values you pass into the function when you call it.
  • return Keyword: Sends a value *out* of the function. If you don't use return, the function returns undefined by default.

Arrow Functions (=>)

The modern, concise, and preferred way to write functions.


                        // Multi-line with explicit return
                        const subtract = (a, b) => {
                            return a - b;
                        };

                        // Single-line with Implicit Return
                        const multiply = (a, b) => a * b;

                        console.log(subtract(10, 4)); // 6
                        console.log(multiply(3, 7));  // 21
                    

Module 3: Complex Data Structures

Storing Collections of Information

Arrays: Ordered Lists

An array is an ordered list of values, accessed by a numerical **index** (starting at 0).


                        const students = ['Alex', 'Jane', 'Peter'];
                        
                        console.log(students[0]); // 'Alex'
                        
                        students.push('Maria'); // Adds to the end
                        
                        // Loop over an array
                        for (let i = 0; i < students.length; i++) {
                            console.log(`Welcome, ${students[i]}!`);
                        }
                    

Objects: Key-Value Pairs

An object is an unordered collection of related data, stored as **key-value pairs**.


                        const student = {
                            firstName: 'Alex',
                            age: 22,
                            isEnrolled: true,
                            courses: ['CS101', 'MATH203']
                        };
                        
                        // Accessing data with Dot Notation
                        console.log(student.firstName); // 'Alex'
                        
                        // Modifying data
                        student.age = 23;
                    

Module 4: Knowledge Check

Interactive Quiz

1. Which of the following is a "falsy" value in JavaScript?

Hint: Think about the value that represents the absence of a number.

  • 'false'
    This is a non-empty string, which is always a "truthy" value.
  • []
    An empty array is an object, and all objects are "truthy".
  • 0
    The number zero is one of the six falsy values in JavaScript.
  • {}
    An empty object is still an object, and all objects are "truthy".

2. What is the final value of i *after* this loop finishes?

for (let i = 0; i < 10; i++) { /* ... */ }

Hint: The loop stops when the condition i < 10 becomes false. What is the first value of i that makes it false?

  • 9
    The last iteration runs when i is 9. Afterward, i is incremented one more time.
  • 10
    While i does become 10, it is declared with let inside the loop, so its scope is limited to the loop block.
  • A ReferenceError occurs
    The variable i is not accessible outside the for loop's block scope. Accessing it would cause a ReferenceError.
  • undefined
    undefined is the value of an unassigned variable. In this case, the variable isn't accessible at all, leading to an error.

3. A function that does not have a return statement will automatically return what value?

Hint: This value represents the state of something that has been declared but not yet assigned.

  • null
    null represents the intentional absence of a value, which must be explicitly returned.
  • undefined
    This is the default return value for any function that completes without hitting a return keyword.
  • false
    A function only returns false if it is explicitly instructed to do so with return false;.
  • An empty string ""
    An empty string is a specific value that must be explicitly returned.

4. How do you access the value associated with the key 'last-name'?

const user = { firstName: 'Jane', 'last-name': 'Doe' };

Hint: Dot notation does not work for property keys that contain special characters like a hyphen.

  • user.last-name
    This would be interpreted as user.last minus name, causing an error. Dot notation cannot have hyphens.
  • user['last-name']
    Bracket notation is required when an object key is a string containing special characters.
  • user.lastName
    The key is defined as the string 'last-name', not lastName. Object keys are case-sensitive and must match exactly.
  • user[1]
    Objects are not indexed by number like arrays; they are accessed by their string keys.

Module 5: Practical Application

In-Class Exercise: The Array Processor

Objective & Setup

To practice looping through arrays and using functions to process data.

Create a file processor.js and add the following starting data:


                        const numbers = [22, 67, 33, 96, 88, 72, 49, 11, 53];
                    

Tasks

  1. Write a function calculateSum(arr) that takes an array, loops through it, and **returns** the sum of all its numbers.
  2. Write a function findMax(arr) that takes an array, loops through it, and **returns** the largest number in the array.
  3. Call your functions with the numbers array and store their results in `const` variables.
  4. Calculate the average by dividing the sum by the array's length.
  5. Use console.log() and template literals to print a report of the results: "Sum: [sum], Average: [avg], Max: [max]".