Zum Inhalt springen

for vs for-in vs for-of loop in Javascript

for loop for-in loop for-of loop
for loop:

We need to provide initialization, condition and increment/decrement to iterate the elements one by one. It is used when the number of iteration is known.

let a=[10,100,1000];
for(let i=0;i<a.length;i++){
    console.log(a[i]);      
}

let str=“Javascript“;
for(let i=0;i<str.length;i++){
    console.log(str[i]);      
}

for-of:
We no need to provide initialization and condition and just follow the syntax to iterate all the elemnts from the array and string. It is used to iterate generator function values too.
//for-of loop
let b=[101,1001,10001];
for(let val of b){
    console.log(val);
}

It is used to iterate generator function values too.
function* newgen(){
    yield „one“;
    yield „two“;
    yield „three“;
}
let val=newgen();
for(let gen of val){
    console.log(gen);   
}

To iterate for and for of values are to be in single values. In object values are in key-value pair so cant iterate using for-of to overcome that for-in loop is used.

for-in:
To iterate object values for-in loop is used. Array and string also we can iterate.

//for-in
// to iterate objects using for-in
let person={
    pname:“AAA“,
    age:11,
    sibling:[„BB“,“CC“],
    hobby(){
        console.log(„Watching movie“);        
    },
    pcolor:{
        hair:“black“,
        eye:“blue“
    }
}
for(let key in person ){
    console.log(person[key]);
   
}
// to iterate array using for-in
let arr=[„a“,’b‘,“c“];
for(let key in arr){
 console.log(arr[key]);
}
// to iterate string using for-in
let st=“Hello“;
for(let key in st){
 console.log(st[key]);
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert