for loop is used to get the array value.
for(var i=0; i<5; i++){
console.log(i);
}
Output:- 0 1 2 3 4
get the Array value
Suppose you have emp array
var emp=["John","Rom","Mathew","Sachin"];
Now, get the Array value
for(var i=0; i < emp.length; i++){
console.log(emp[i]);
}
Output:- John Rom Mathew Sachin
Note:- emp.length is used to count the number of array element.
get the array element value from last element to first element.
var emp=["John","Rom","Mathew","Sachin"];
for(var i=emp.length-1; i >= 0; i--){
console.log(emp[i]);
}
Output:- Sachin Mathew Rom John
Changes the increment
for(var i=0; i<=10; i=i+2)
{
console.log(i);
}
Output:- 0 2 4 6 8 10
Javascript for loop – Interview Questions
Q 1: What is a for loop?
Ans: A loop with initialization, condition, and increment.
Q 2: Syntax of the for loop?
Ans: for(init; condition; increment).
Q 3: Is the for loop entry-controlled?
Ans: Yes.
Q 4: Can a for loop be nested?
Ans: Yes.
Q 5: Use case?
Ans: Iterating arrays.
Javascript for loop – Objective Questions (MCQs)
Q1. The for loop is used when the number of iterations is ______.
Q2. How many parts does a for loop have?
Q3. Which part executes only once in a for loop?
Q4. Which keyword exits a loop immediately?
Q5. Which loop is best for array index-based iteration?