JavaScript For Loop
for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement.
- Initialization: Runs once before the loop starts to set up a counter variable.
- Condition: Evaluated before every iteration; if true, the loop continues.
- Afterthought: Runs at the end of each iteration, usually to increment or decrement the counter.
Syntax
for (initialization; condition; afterthought) {
// Code to execute during each iteration
}
Flowchart

Example 1:Counting up to 5
for (let i = 1; i <= 5; i++) {
console.log(i); // 1, 2, 3, 4, 5
}
Example 2: For loop to print table of a number
let x = 5
for (let i = 1; i <= 10; i++) {
console.log(x * i); // 5 10 15 20 25 30 35 40 45 50
}
do...while loop
A do...while loop in JavaScript is an exit-controlled control flow statement that executes a block of code at least once before checking if a specified condition is true. If the condition evaluates to true, the loop repeats; if false, the loop terminates.
Syntax
The syntax requires the do keyword followed by a code block, and finishes with the while keyword and a boolean condition.
do {
// Code block to be executed
} while (condition);
Example
let status = false;
do {
console.log("This message prints exactly once!");
} while (status === true);// This message prints exactly once!
Function
A JavaScript function is a reusable block of code designed to perform a specific task. It executes only when it is called.They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.
Arguments
In JavaScript, arguments are the actual values you pass into a function when you called.
function greet(name) { // name = parameter
console.log("Hello " + name);
}
greet("Ezhil"); // "Ezhil" = argument
Parameters
Parameters are the variables declared in the function definition that receive values from arguments when the function is called.
"Declared in the function definition" means the variables written inside the function's parentheses when creating the function.
Example
function add(a, b) {
console.log(a + b);//30
}
add(10, 20);
a and b → Parameters
10 and 20 → Arguments
Tricky Interview Questions
1.What happens if arguments are missing?
function add(a, b) {
console.log(a + b);
}
add(10);//Nan (because b is undefined)
2.Why is do...while different from while?
do...while executes at least once.
let x = 10;
do {
console.log("Hello");
} while (x < 5);//Hello
References
https://www.geeksforgeeks.org/javascript/javascript-for-loop/
Top comments (0)