Loops In Javascript
A loop is concept of repeating until not false the condition. JavaScript has several loops with different conditions, these are following
- for loop
- while loop
- do while
- for in
Basically you can use any loop in your program , but each has some conditions ;by the help of these you can understand its use .
Conditions
- for loop is use for perfect time means you will know that how many time your loop need to run after that you will get its desired value for example: if you want to print 1-10 digits that means you need to run your loop ten times .
- While loop is use, when you not know at which value you get your desired output
- do while loop is same as while loop
- for in loop use for array.
for loop syntax
for(initialvalue; condition;incrementinvalue)
{
//your code
}
{
//your code
}
Example
for(var i=0;i<=10;i++) { console.log(i); }
- it print digits from 0 to 10
While Loop Syntax
while(condition)
{
//your code
}
{
//your code
}
Example while loop
var bool=true; while(bool){ console.log(bool); bool=false; }
do while Loop Syntax
do
{
//your code
}while(condition)
{
//your code
}while(condition)
Example
var bool=true; do{ console.log(bool); bool=false; }while(bool)
for in loop syntax
for (variablename in object){
statement or block to execute
}
statement or block to execute
}
Example
var digit ={"A":1,"B":2,"C":3} for (var i in digit) { console.log( i+": "+digit[i]); }
- Here i create a variable digit ,which is object and it has several properties
- In loop i take the property name and i pass this in object index and it call that value .
for in loop not need any condition for complete the loop,because it work at the end of the property of object
Join the discussion