Repetition, Reusability, and Collections
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
A condition (if (...)) doesn't strictly need truetrue` to pass. It only needs a "truthy" value.
JavaScript has only **6 Falsy Values**. Memorize them.
''
(an empty string)Everything else is Truthy! (e.g., 'hello', 52, [], {}, 'false')
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'
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}`);
}
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**!
// 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!"
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
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]}!`);
}
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;
1. Which of the following is a "falsy" value in JavaScript?
Hint: Think about the value that represents the absence of a number.
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?
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.
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.
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];