Loops are used to repeatedly execute a block of code until a specified condition is met.
Definition: A for
loop repeats a block of code a specific number of times, usually when you know how many times you want it to run.
How it works: It runs the initialization once, checks the condition each time, runs the code if the condition is true, and updates the counter after each run.
for (let i = 0; i <= 10; i++) {
console.log(`Hello ${i}`);
}
Output:
Definition: A while
loop runs a block of code as long as a specified condition is true, often used when you don't know how many times it should run.
How it works: It checks the condition before each run and keeps looping until the condition becomes false or a break
statement stops it.
let number = 0;
while (true) {
console.log(`Hello ${number}`);
number++;
if (number >= 10) {
break;
}
}
Output:
Functions are reusable blocks of code that perform a specific task. You can define a function once and call it whenever needed.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Justin");
Output:
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3));
Output:
Variables store data that can be used and changed during a program’s execution.
let name = "JavaScript";
let version = 2023;
console.log("Language:", name);
console.log("Version:", version);
Output:
const pi = 3.14;
let counter = 0;
Explanation:
Test your understanding of loops and functions by answering the following multiple-choice questions.