Loading...

Loops in JavaScript

Basic Loops

Loops are just blocks of code that repeat until a condition is met. These are central to programming and can serve many purposes. This article will tackle the different JavaScript loop syntax available.

BREAK & CONTINUE

Before getting into the loops, we want to know how to control the loops, if needed.

  • break stops the loop.
  • continue effectively passes that step in a switch or iteration of a loop.

For this example, ignore the loop itself as we will get into that shortly. For now, just notice how break and continue work.

for (i = 1; i < 7; i++) {
    if (i === 3) {
        console.log('Continuing past ' + i);
        continue;
    }
    if (i === 5) {
        console.log('Breaking on ' + i);
        break;
    }
    console.log(' | ' + i + ' time')
}
//  RESULT: | 1 time
//          | 2 time
//          Continuing past 3
//          | 4 time
//          Breaking on 5

"for" Loop

for(initialization; condition, increment or decrement) { ...body }
let nLoop = 3;
for (let i = 0; i <= nLoop; i++) {
    console.log( "Number is " + i);
}

//  RESULT: Number is 0
//          Number is 1
//          Number is 2
//          Number is 3
                        

"while" Loop

while(condition - loops as long as true) { ...body }
nLoop = 3;
i = 0;
while (i < nLoop) {
    i++;
   console.log("While the number is " + i);
}

//  RESULT: While the number is 1
//          While the number is 2
//          While the number is 3

                        

"do-while" Loop

do(condition - loops as long as true) { ...body }
nLoop = 5;
i = 7;
do {
   console.log("Done once");
} while (i <= nLoop);

// RESULT: Done once
                        

This combines do-while and if() to take a number and list all numbers except for those divisible by 3

    // let prmpt = prompt("enter a number", "Enter here");
    prmpt = 4
    let ii = 0;

    do {

        let divBy3 = ii % 3;

        if (divBy3 != 0) {

            console.log('Do, while and if ' + ii);
        }

        ii++;
    } while (ii <= prmpt);
//  RESULT: Do, while and if  1
//          Do, while and if  2
//          Do, while and if  4
                        

Closure

Closure functions - lexically scoped or scope chaining - A function inside of a function. The variables will remain in the Memory Heap while an internal (lexically scoped) reference remains.

function firstOne() {

    let output = "the first one, ";

    function secondOne() {

        return output += "the second one";
    }
    secondOne();

    return output;
}
firstOne();
// OUTPUT: "the first one, the second one"
                        

Another good closure example

The grandpa variable in the example below remains in memory after a() runs and is removed automatically during a built-in JS memory cleaning process often called garbage collection). The grandpa variable remains because the lexical environment is a closure

On the contrary, the variable someVar will be removed during garbage collection because nothing else in this lexical environment refers to it.

Like grandpa, the father variable remains after a() runs and after the memory clearing or garbage collection

To bring all of this together, when c() runs, it returns three of the four variables created when a() and b() ran, even though both of those function have already been cleared from memory. Because there was a reference to these three variables, the content of each variable is available due to closure.

function a() {
    let grandpa = 'grandpa';
    let someVar = 'someValue'
    return function b() {
        let father = 'father';
        return function c() {
            let son = 'son';
            return `${grandpa} > ${father} > ${son} >`
        }
    }
}

a(); //	RESULT: The function
a()(); //	RESULT: The function
a()()(); //	RESULT: "grandpa > father > son >"
                        

Here we use closure, but this is written in long form. This will provide a good comparison to the example that follows. That example is the same function using shorthand expression.

function nameFunct {
    return function(name) {
        return function(name2) {
            return console.log(`${string} ${name} ${name2}`)
        }
    }
}
                        

Here is the shorthand version of the above with Arrow functions

function nameFunct(firstName) {
    return function(secondName) {
        return function(thirdName) {
            return console.log(`${firstName} ${secondName} ${thirdName}`)
        }
    }
}
nameFunct('First');
nameFunct('First')('Second');
nameFunct('First')('Second')('Third'); //  RESULT: "First Second Third "
nameFunct('First')('Second')(''); //	RESULT: "First Second "
nameFunct('First')('')('Third'); //  RESULT: "First  Third "
                        

For-Of Loop

The for-of loop is a simple loop syntax that allows for breaks and more.

for...of
    loops can be used on:
  • Strings
  • Arrays
  • Array-like objects (arguments or NodeList)
  • TypedArray
  • Maps
  • Sets
  • User-defined iterables
for(let value of object) {...logic}

Difference between for...in and for...of

The for...in statement loops the enumerable properties of an object. Essencially, this goes through each name of a property. With arrays, it will provide each index number.

The for...of loop iterates over values that the iterable object defines to be iterated over. For arrays, this will itterate over the values. Object will not work as they are only enumerable and not iteratable. This will run through each value

↓ Examples ↓

//////////////////////////
//	The following shows the 
// difference of 'for-of' 
// and 'for-in' with an Object
//////////////////////////
myObj = {
    'apples': 7,
    'berries': 10,
    'bananas': 3
};

for (item in myObj) {
    console.log(item)
}
//	RESULT	'apples'
//			'berries'
//			'bananas' 

for (item of myObj) {
    console.log(item)
}
//	RESULT	'myObj is not iterable'



//////////////////////////
// The following shows the
// difference for arrays 
// using 'for-of' and 'for-in'
/////////////////////////
myArray = ['apples', 'berries', 'bananas'];

for (item in myArray) {
    console.log('item', item)
}
//	RESULT	'0'
//			'1'
//			'2' 


for (item of myArray) {
    console.log('item', item)
}
//	RESULT	'apples'
//			'berries'
//			'bananas'



//////////////////////////
// Using a 'for' loop 
//////////////////////////
let names = ["John", "Bob", "Rick"];

for (let value of names) {
    console.log(value); //	RESULT: John 	Bob 	Rick
}



//////////////////////////
//	Using break
//////////////////////////
let names = ["John", "Bob", "Rick"];

for (let value of names) {
    console.log(value); //	RESULT: "John" (it ends at "Bob")	
    if (value = "Bob") break;
}



//////////////////////////
//	Separate string characters
//////////////////////////
let iterable = 'wow';

for (let value of iterable) {
    console.log(value);
}
//	RESULT: "w"
//          "o"
//          "w"



//////////////////////////
//	Iterating over map
//////////////////////////
let myMap = new Map([
    ['Tim', 18],
    ['Susan', 27],
    ['Tina', 32]
]);

for (let entry of myMap) {
    console.log(entry);
}
// ['Tim', 18]
// ['Susan', 27]
// ['Tina', 32]

for (let [key, value] of myMap) {
    console.log(value);
}
// 18
// 27
// 32



//////////////////////////
//	Using for...of with 
//  function arguments
//////////////////////////
function myFunct() {
    for (let argument of arguments) {
        console.log(argument);
    }
};

myFunct(1, 2, 3);
// 1
// 2
// 3
                        
More examples on MDN →

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top