JavaScript Loops
What is Loops?
- initializations usually initializes one or more loop counters.
for loop example
Loops offer a quick and easy way to do something repeatedly. Loops can execute a block of code a number of times.
JavaScript supports different kind of loops
- for loop
- for/in loop
- for/of loop
- while loop
- do/while loop
- if the value of condition is true, the loop statement execute. If the value of condition is false, the for loop terminates.
- increment increase or decrease the initialization value.
(for leti=1;i<=10;i++){ console.log(i + " "); }//output: 1 2 3 4 5 6 7 8 9 10for in loop syntax
for(variable in object){ // Your Code Here }The JavaScript for in statement loops through the properties of an object it means, if you use for in with an object then the variable would be all key this object. If you use for in with an array then the variable would be all index of this array.
for in loop Example
let obj = { cars: "BMW", fruits: "Apple"}; for(x in obj){ console.log(x); //Output:"cars", "fruits" } let arr = ["Hello", "Hey", "Hi"]; for (x in arr){ console.log(x); // "0", "1", "2" }for of loop syntax
for(variable of object) { // Your Code Here }The JavaScript for of statement loops through the values of an iterable objects for of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, Node Lists and more. if you use for of with an array then the variable would be all elements of this array.
for of loop example
let arr = ["Hello", "Hey", "Hi"]; for(x of arr) { console.log(x); //output: "Hello", "Hey", "Hi" }while loop executes until condition becomes false. The while loops through a block of code as long as specified condition is true. The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
while loop exmple:
i=1; while(i<=10){ console.log(i + " "); i++; }//Output : 1 2 3 4 5 6 7 8 9 10do while loop executes until condition becomes false. do while loop always executes once before condition check.
do while example:
i=1; do{ console.log(i + " "); i++; }while(i<=10)// output : 1 2 3 4 5 6 7 8 9 10
No comments: