Loops in JavaScript

Any programming language’s execution is dependant upon two aspects first squeezing code together as a single identity, and second being executing same code statements again and again.

For doing first part which is squeezing code together JavaScript uses Objects, Functions, Compound Statements while for second part(Repeatatively executing same code) JavaScript uses Loops.

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns false.
Here is the list of common loops in JavaScript –
• while loop
• do while loop
• for loop
• for in loop

JavaScript while loop

JavaScript while loop has syntax as

initialize;
while(test) {
	statement;
	update;
}

test would evaluate to Boolean
update could be anything like incrementing or decrementing

For executing this JavaScript interpreter evaluates test expression if it’s true then it execute statement, otherwise interpreter would just move onto next statement in code. JavaScript while loop will keeping executing statement inside it, until test expression becomes false. Moreover if test expression never evaluates to false then it would be an infinite loop.

var count = 5;
while (count < 9) {
	console.log(count);
	count++;
}
// Will print out 5, 6, 7, 8 on the console of a browser
For this piece of code, JavaScript interpreter would compute
count < 9 and execute inner statements until count < 9 expression
becomes false

Note – while loop doesn’t need a semicolon at end of code block

do while JavaScript loop

JavaScript do while loop has syntax as –

do{
	statement
} while(expression);

JavaScript’s do while loop almost executes in same way as while loop, just a little difference is that do while loop would always execute atleast one. Below is the procedure which JavaScript interpreter follows for executing do while loop

  1. First execute statement inside do while loop
  2. Compute expression if it evaluates to true
  3. Execute statement until expression turns false

Below is an example of do while JavaScript code –

var car = "";
var i = 0;

do {
	car += "Tesla car " + i;
	i++;
} while (i < 3);

// This will turn car variable into 
Tesla car 0 Tesla car 1 Tesla car 2 

Note – Make sure to put a colon at end of while(expression)

for loop JavaScript

JavaScript’s For loop is made up of three components which are initialize, test, update.
• Initialize for setting up initial values of variables

• Test for comparing the value of changing variable with some loop parameter(often coded by the programmer)

• Update for changing value of variable in loop

• Initialize, test, update are separated by colon inside rounded parenthesis

JavaScript loop’s working is kind of similar as that of while loop. Below is syntax of for loop in JavaScript

for(initialize; test; increment){
	     statement
}

Note – In a for loop there can be more than one individual component like there can be 2 initialize.

You can may be eliminate initialize component from body of for loop

Below is an example of simple JavaScript for loop –

for(i = 0; i < 5; i++) {
	console.log(i);
}

// This piece of code will print
0
1
2
3
4

for in JavaScript Loop

JavaScript’s for in loop is made up of two components and usual statements, these components are variable, object. The syntax of JavaScript’s for in loop is –

for (variable in object){
	statement
}

This loop is executed by JavaScript’s interpreter following these steps –
1) Firstly interpreter would evaluate object, if in case this evaluates to null/undefined then interpreter would move to next line of code instead of executing loop.

2) If object doesn’t evaluates to null/undefined then interpreter will convert object to a wrapper object.

3) After converting object -> wrapper object, interpreter will look for variable as a property name of wrapper object. If interpreter does finds property name then further body of for in loop will be executed.

If your not aware of Wrapper Objects in JavaScript then you can check other article on this website which I put together explaining everything about Wrapper Objects in JavaScript – JavaScript Wrapper Object.

Mostly for in loop is used for traversing/going through array values in JavaScript. Below is a code example for that –

laptops = ["Mac", "HP", "Windows"] // JavaScript Array

//JavaScript for loop
for(var i=0; i < laptops.length; i++){
	console.log(laptops[i]);
}

//JavaScript in for loop
for(var i in laptops){
	console.log(laptops[i]);
}

// Both of these loops will print same values on console
"Mac"
"HP"
"Windows"

Note – for(var i in array_name) means i will be index values of elements in array_name one by one.
i would be 0, 1, 2, 3 …….. upto (length of array – 1)

Conclusion

JavaScript loops are quite handy for doing repetitive code execution, with just a few lines of code a lot of work could be done. Here on this article I’ve covered fundamentals of JavaScript loops, moroever time complexity of loop execution should also be considered by a programmer before making a choice of using one out of all available loops. Perhaps sometimes later I would put together an article on time complexity of loops in JavaScript as well.

But for time being if you’ve any question about JavaScript Loops then let me know in comments, I would try to reply as soon as possible for me.

Moreover if your learning JavaScript Programming Language then I’ve put together a number of articles as well specifically converting coding in JavaScript. If you want to have a look as those, you can go here – JavaScirpt Computer Science Hub.

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

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

Recent Posts