<JavaScript />

Loops & Functions

Loops & Functions

Loops & Functions

Loops & Functions

Learn

About

🔁 Loops

Loops are used to repeatedly execute a block of code until a specified condition is met.

Examples

For Loop

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:

While Loop

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

Functions are reusable blocks of code that perform a specific task. You can define a function once and call it whenever needed.

Examples

Function Declaration

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Justin");

Output:

Arrow Function

const add = (a, b) => {
  return a + b;
};

console.log(add(5, 3));

Output:

Learn

📦 Variables

Variables store data that can be used and changed during a program’s execution.

Examples

Basic Variable Declaration

let name = "JavaScript";
let version = 2023;
console.log("Language:", name);
console.log("Version:", version);
        

Output:

const vs let

const pi = 3.14;
let counter = 0;
        

Explanation:

🧠 Quiz: Loops & Functions

Test your understanding of loops and functions by answering the following multiple-choice questions.