General Loops

For Loop

You should use for loop, when You know, how many times is gonna run. How many iteration’s gonna have. Use a while loop, when you don’t.

for(let i = 0; i <= 10; i++){
    console.log('Number ' + i);
}

Continue statement

for(let i = 1; i <= 5; i++){
    if(i === 3){
        console.log('3 is my favorite number');
        continue;
    }
    console.log('Number ' + i);
}
Number 1
Number 2
3 is my favorite number 
Number 4
Number 5

Break statement

for(let i = 1; i <= 5; i++){
    if(i === 3){
        console.log('3 is my favorite number');
        continue;
    }
    if(i === 4){
        console.log('Stop the loop');
        break;
    }
    console.log('Number ' + i);
}
Number 1
Number 2
3 is my favorite number 
Stop the loop

While Loop

let i = 0;

while(i <= 10){
    console.log('Number ' + i);
    i++;
}

Do While Loop

It’s always gonna run at least once, no matter what.

let i = 0;

do{
    console.log('Number ' + i);
    i++;
}
while(i < 100);

Loop through array

For Loop

const cars = ['Ford', 'KIA', 'Toyota', 'Honda'];

for(let i = 0; i < cars.length; i++){
    console.log(cars[i]);
}
Ford
KIA
Toyota
Honda

Foreach Array Loop

cars.forEach(function(car){
    console.log(car);
});
Ford
KIA
Toyota
Honda

Access to key value pairs

cars.forEach(function(car, index){
    console.log(`${index} : ${car}`);
});
0 : Ford 
1 : KIA 
2 : Toyota 
3 : Honda

Map

We also have a method called map. It’s basically used to return different array.

const users = [
    {id:1, name: 'John'},
    {id:2, name: 'Jack'},
    {id:3, name: 'James'}
];

const ids = users.map(function(user){
    return user.id;
});

console.log(ids)
const names = users.map(function(user){
    return user.name;
});

console.log(names);

For in loop – Which is often used for objects

Let’s create a single object called user

const user = {
    firstName: 'John',
    lastName: 'Jack',
    age: 36
}

Access to key

for(let x in user){
    console.log(x);
}
firstName
lastName
age

Access to the object with key value paris

for(let x in user){
    console.log(`${x} : ${user[x]}`);
}
firstName : John
lastName : Jack
age : 36
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *