Sunday, November 18, 2018

Understanding Difference Between For, For…In and ForEach Loop In Javascript

This tutorial explains basic implementation of  ForFor…In and ForEach loop in Javascript and it's working in real time scenarios. Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. Lets see the below example that helps you to build more understanding on  For,  For…In and ForEach loops. 


Understanding Difference Between For,  For…In and ForEach Loop In Javascript

For Loop

The for loop is used when you know in advance how many times the script should run. lets see the below example for  For loop syntax, it will iterate for nth times.( depending upon looping times specify the nth value.)

Syntax :
for (i = 0; i < n; i++) { 
  // do something
}

Example 
const array = ['skptricks', 'php', 'java'];
for (i = 0; i < array.length; i++) { 
  console.log(array[i])
}

Output:
--------------
> "skptricks"
> "php"
> "java"

For…In

for...in is used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable. Lets see the for...in syntax :
Syntax:
for (variable in object) {  
  // do something
}

Example-1 
In this example we will iterate the string character value using For...in looping condition.
const string = 'skptricks';
for (let character in string) {  
    console.log(string[character])
}

Output:
--------------
> "s"
> "k"
> "p"
> "t"
> "r"
> "i"
> "c"
> "k"
> "s"

Example-2 
In this example we will iterate the object value using For...in looping condition.
const obj = {  
  a: 1,
  b: 2,
  c: 3,
  d: 4
}

for (let element in obj ) {
  console.log(`${element} = ${obj[element]}`);
}

Output:
--------------
> "a = 1"
> "b = 2"
> "c = 3"
> "d = 4"

Example-3 
In this example we will iterate the array value using For...in looping condition.
const arr = ['skptricks', 'php', 'android'];
for (let i in arr) {  
  console.log(arr[i])
}

Output:
--------------
> "skptricks" > "php" > "android"

ForEach

forEach is an Array method that we can use to execute a function on each element in an array. It can only be used on Arrays, Maps, and Sets. Lets see the below example:

Example 
const arr = ['skptricks', 'php', 'android'];
arr.forEach(element => {
  console.log(element);
});

Output:
--------------
> "skptricks" > "php" > "android"

This is all about  For,  For…In and ForEach Loop In Javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment