Search This Blog

2020/12/30

FOR IN & FOR OF Loops in javascript

For In loop is used to loop through keys of an object while for of loop is used to loop through array element.


For OF Loop:

Consider following array ,we want to iterate through values of this array.

Example 1:

let arr = ["sagar","sangram","sachin","swapnil","gaurav","swara"]

for(let elt of arr)

{

console.log(`Element ${elt}`);

}

Output:

Element sagar

Element sangram

Element sachin

Element swapnil

Element gaurav

Element swara

 

Example 2:As we know string is essentially character array.

let str ="india is my country";

for(let char of str)

{

console.log(`${char}`);

}

Output:

i

n

d

i

a

i

s

m

y

c

o

u

n

t

r

y


For In Loop:consider following code snippet.Our object obj keys we want to iterate.It can be done as follows


Example 3:

let obj = {

name:"sangram",

city:"mumbai",

state:"maharashtra",

pin:"416602",

language:"marathi",

knowEnglish :"yes"

}

for(let key in obj)

{

console.log(`Key: ${key} Value: ${obj[key]}` );

}

Output:

Key: name Value: sangram

Key: city Value: mumbai

Key: state Value: maharashtra

Key: pin Value: 416602

Key: language Value: marathi

Key: knowEnglish Value: yes


Here we get key inside loop from which we find value as obj[key].

 We should use this alternate implementation of traditional for loop whenever feasible it is simple & concise.

Lets take look at traditional way to loop object keys.

 Traditional Way using for loop:

Example 4:

let obj = {

name:"sangram",

city:"mumbai",

state:"maharashtra",

pin:"416602",

language:"marathi",

knowEnglish :"yes"

}

for(let i=0;i < Object.keys(obj).length;i++)

{

console.log(`Key: ${Object.keys(obj)[i]} and Value ${obj[Object.keys(obj)[i]]}`)

}

Output:

Key: name and Value sangram

Key: city and Value mumbai

Key: state and Value maharashtra

Key: pin and Value 416602

Key: language and Value marathi

Key: knowEnglish and Value yes


One more way of looping using Object.entries:

Example 5:

for(let entry of Object.entries(obj))

{

console.log(`Key: ${entry[0]} # Value: ${entry[1]}`)

}

Output:

Key: name # Value: sangram

Key: city # Value: mumbai

Key: state # Value: maharashtra

Key: pin # Value: 416602

Key: language # Value: marathi

Key: knowEnglish # Value: yes


we can also use foreach on object keys array to loop through.


Example 6:

let entries = Object.entries(obj)

for(let entry of entries)

{

console.log(`Key: ${entry[0]} # Value: ${entry[1]}`)

}


let keys = Object.keys(obj);

keys.forEach((element,index) => {

console.log(`Key: ${element} , Index: ${index} ,Value:${obj[element]}`)

});


Output:

Key: name , Index: 0 ,Value:sangram

Key: city , Index: 1 ,Value:mumbai

Key: state , Index: 2 ,Value:maharashtra

Key: pin , Index: 3 ,Value:416602

Key: language , Index: 4 ,Value:marathi

Key: knowEnglish , Index: 5 ,Value:yes

No comments:

Post a Comment