Making Decisions: Conditionals and Loops
So far, your code has run top to bottom. Real programs need to make decisions and repeat work. A conditional is a statement that runs code only when a condition is true. A loop is a statement that repeats code.
const age = 20;
if (age >= 18) {
console.log('Adult');
} else {
console.log('Minor');
}
for (let i = 1; i <= 3; i++) {
console.log('Lap ' + i);
}The if statement checks a condition. If it is true, the first block runs; otherwise, the else block runs. The for loop repeats three times: it starts i at 1, keeps going while i <= 3, and adds 1 each pass.
Functions: Reusing Logic
A function is a named block of code you can run whenever you need it. Functions let you write logic once and reuse it.
function double(n) {
return n * 2;
}
console.log(double(4)); // 8
console.log(double(21)); // 42The word return sends a value back to whoever called the function.
Working with Collections of Data: Arrays
An array is an ordered list of values. You often want to do the same thing to every item — that is where loops and array methods shine.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens); // [2, 4]map builds a new array by transforming each item. filter builds a new array with only the items that pass a test. An arrow function like n => n * 2 is a short way to write a small function.
Modeling Data with Objects
An object is a collection of named values, called properties. Objects are how you model one thing, like a book.
const book = {
title: 'Exploring JS',
edition: 2,
describe() {
return `${this.title} (edition ${this.edition})`;
}
};
console.log(book.title); // Exploring JS
console.log(book['edition']); // 2
console.log(book.describe()); // Exploring JS (edition 2)Use a dot (book.title) or brackets (book['edition']) to read a property. this inside a method refers to the object itself.
Scope and Closures
Scope is where a variable can be seen in your code. Variables declared with let and const inside a block or function exist only there.
function counter() {
let count = 0;
return function () {
count++;
return count;
};
}
const next = counter();
console.log(next()); // 1
console.log(next()); // 2A closure is a function that remembers the variables from where it was created. next remembers count, so each call keeps counting.
Exercise
What does [1, 2, 3].map(n => n * 10) return?
Show answer
[10, 20, 30] — map transforms each item into the new array.
Exercise
Why does next() return 1, then 2?
Show answer
The inner function is a closure that remembers count, so it keeps incrementing the same variable across calls.
Spotted a mistake, or code that does not work?