JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Loop Which Made Life Easy

JavaScript Loop Which Made Life Easy

In this tutorial, you’ll be going to learn a javascript loop which is for loop, while loop, and do-while loop. All three of them are like a legend that you will found in most of the language.

But javascript also introduces two other newcomers which help in especially dealing with an array, object, map, set, etc like stuff. So here, they are for…of loop and for…in loop.

JavaScript Loop

The javaScript loop’s main task is to repeat a certain block of code until a certain condition is fully filled. As I already mentioned above 5 types of a loop which we will be going to discuss in detail.

But all have their own of dealing with string, array, object, map, set, etc. Loops can execute a block of code a number of times.

When developer talks about iteration or iterating over string, array, object, etc. It’s actually same as looping.

JavaScript loop is a highly used code in day-to-day task and project requirements which definitely made life easy. Let’s start to learn all the javascript loop in detail.

Want to learn something more

  1. How to remove duplicates from javascript array
  2. How To Loop Through An Array In JavaScript

JavaScript for loop

for loop is currently the most used looping execute a certain block of code repeatedly based on condition pass to for loop. Why it’s mostly used because it’s the first loop we learn and it’s easy to use compared to others.

for loop Syntax

for loop syntax contain three statements, initialization execute one time before the execution of the code block. test condition defines the condition for executing the code block and the last iteration statement is executed (every time) after the code block has been executed.

for (initialization; test condition; iteration statement) {
   // code block to be executed until test condition is true
}

Some Example of Javascript for loop

Here, you’ll learn some use case or example of for loop.

Basic Example of for loop

In this loop, i assign with 0 and on the condition i < 5 which means the loop run until the value of i less than 5 and in the last after every iteration value of i is increment by 1.

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

// 0, 1, 2, 3, 4

Iterate array with for loop

Here, we loop over an array until all elements in that array get printed. Which means up to the length of the array.

const array = [10, 20, 30, 40, 50];
for(let i = 0; i < array.length; i++){
  console.log(array[i]);
}
//  10, 20, 30, 40, 50

Iterate string with for loop

String is also iterable value like an array upto the length of string.

let name = "JS Startup";
for(let i = 0; i < name.length; i++){
  console.log(name[i]);
}
//  J,S, ,S,t,a,r,t,u,p

At last, there are lot of stuff that you can do with for loop like pattern printing, modify array and object values etc.

Note: Wrong statement in the for loop statement sometime leads to infinite loop.

JavaScript While Loop

while loop also helps to accomplish the same thing which can for loop does. while loop loops through a block of code while a specified condition is true.

Compare to for loop, while loop only contains one statement rather than 3 statements. But that statement still exist outside or inside of a while loop.

while loop Syntax

In the below while loop syntax, you can see their is only condition pass to while nothing else. If condition is true then it execute block of code.

while (condition) {
  // code block to be executed until condition return true
}

Some Example of Javascript while loop

Here, you’ll learn some use cases or examples of a while loop. We will use the same example of for loop so you can check the difference.

Basic Example of while loop

In this javascript loop, first i is declared outside the loop and assign with 0 and on the condition i < 5 which means the loop run until the value of i less than 5 and in the last i value is incremented inside the while loop.

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

// 0, 1, 2, 3, 4

Iterate array with while loop

Here, we use while loop over an array until all elements in that array get printed. Which means up to the length of the array.

const array = [10, 20, 30, 40, 50];
let i = 0;
while(i < array.length){
  console.log(array[i]);
  i++;
}
//  10, 20, 30, 40, 50

Iterate string with while loop

Same goe with string also because string is iterable value like an array.

let name = "JS Startup";
let i = 0;
while(i < name.length){
  console.log(name[i]);
   i++
}
//  J,S, ,S,t,a,r,t,u,p

Comparing for and while Loop

Both loop work same as you can see the output. Only different is the placement of statement. But mostly, everyone prefer for loop as you can define all the statement at one place.

Let’s take one example of each in for loop & while loop look same.

for loop exmaple

let array = ["Hi" "JS", "Startup"];
let i = 0;

for (;array[i];) {
 console.log(array[i])
  i++;
}

// Hi, JS, Startup

while loop example

let array = ["Hi" "JS", "Startup"];
let i = 0;

while (array[i]) {
 console.log(array[i])
  i++;
}

// Hi, JS, Startup

Above both the example runs until there is a value in array and they look similar as for also only contain conditional statement.

JavaScript do while loop

In javascript, do-while is a variant of while loop as while loop still in the do-while. Like for loop and while loop, which never runs until condition satisfied that not the condition with do-while.

do while at least run once then looks for condition, if the condition is met then it run continuously like a while loop. do while containing two parts, do which run once and then based on condition & while which check for the condition.

do while loop syntax

In the below loop, do block run once at least then it check for while condition. If condition return true, the do run repeatedly until condition return true but if it return false then do code block not run.

do{
// code block to be executed once then based on while condition
}
while (condition)

Some Example of Javascript while loop

Here, you’ll learn some use cases or examples of a do-while loop. We can use the same example as above but do while loop gives the same output if all condition is true. But if the condition failed in the first occurrence then output is changed.

Basic Example of do while loop with true condition

Here, we loop until i values is less than 5 whose output is similar to for loop and while loop.

let i = 0;
do {
  console.log(i);
  i++;
} while(i < 5)

// 0, 1, 2, 3, 4

Basic Example of do while loop with false condition

Now, we use the same example as above but instead of 5 we use 0. If it’s a for loop or while loop code not even runs. But that not the case with do while loop.

let i = 0;
do {
  console.log(i);
  i++;
} while(i < 0)

// 0

As, you can see we get a 0 because do block run once then it check for failed condition Which stop the execution.

You can check the same scenario with array and string also if everything is fine then it gave same result as for and while loop. But if condition return false then output of for and while loop not matches with do while.

Do while is not bad to used because it’s all depend on the requirement of task. What you need to accomplish. There are scenario, where you need do block of do while to run once.

Welcome Newcomer

Above, three loops can find out in c, c++, Php, etc but javascript also introduces two new loops which are for…of and for…in because we web developers mainly deals with iterable types value like array & object.

And having another variable like i and then incrementing or decrementing the value of i until to get value in iterable types. These two loops solved this problem but don’t mean they work on the same iterable types. Let’s get into more detail.

Wait, Want to dig in more into javascript

  1. Important Javascript Array Methods You Should Know
  2. Different ways to declare function in javascript

JavaScript for…of loop

In javascript, for…of loop loops through a value of iterable objects like Array, Map, Set, String, arguments, etc.

Note: This loop iterated over property values.

for…of loop syntax

In this, we have a variable which contains the value of iterable object like an array, map, set, etc. And it’s value changes as the loop iterate until the length of iterable.

for (variable of iterable) { 
statement 
}

Some Example of Javascript for…of loop

Here, you’ll learn some use cases or examples of a for…of loop. We can use the same example above like using string, array but not repeat a block of code with specified conditions like in for, while, and do-while loop. Because it works on iterable types.

Iterating string with for…of loop

In below example, we use a string “jsstartup” and iterate over it and get each character separately.

const name = 'jsstartup';

for (const char of name) {
  console.log(char);
}

// 'j','s','s','t','a','r','t','u','p'

Iterating array with for…of loop

Now, we use an array to loop through and like other loops here we just need one variable which contain a value of array at each iteration.

const array = [10, 20, 30, 40];

for (const value of array) {
  console.log(value);
}

// 10, 20, 30, 40

Iterating Map with for…of loop

The Map object is iterable over its key and value pairs. As map is like an object.

const map = new Map();
map.set('name', 'JS');
map.set('value', 'Startup');

for (const [key, value] of map) {
  console.log(key, value);
}

// 'name', 'JS'
// 'value', 'Startup'

Iterating Set with for…of loop

The Set object is iterable over its items. Set is like an array but only store unique values in it.

const set = new Set(['Hi', 'Ajay', 'Yadav']);

for (const item of set) {
  console.log(item);
}

// 'Hi', 'Ajay', 'Yadav'

Iterating arguments with for…of loop

You can iterate over the arguments object to examine all of the parameters passed to it.

(function() {
  for (const argument of arguments) {
    console.log(argument);
  }
})(10, 20, 30);

// 10, 20, 30

JavaScript for…in loop

In javascript, you have so many loops to iterate over a string, array, map, set, arguments, etc. But what about the javascript object because it also needs to be iterate like others.

Before the for..in loop, it’s very difficult to iterate over it. But now, it’s easy as for…of loop. for…in loop loops through the properties of an object and array. But with an array, it’s not recommended to use for..in.

Note: This loop iterated over property name.

for…in loop syntax

In this, we also have a variable but it contains the property of object & array. And it’s value changes as the loop iterate until the no of a key in the object and index in the array.

for (variable in object){
  statement
}

Some Example of Javascript for…in loop

Here, you’ll learn some use cases or examples of a for…in loop. We can use the same example above like using array and object but not string.

Iterating object with for…in

In below example, we iterate an object with two keys and variable contain key of object which changes in each iteration.

const detail = {
  name : "JS",
  phone : "+91"
}

for(const property in detail){
  console.log(property, detail[property]);
}

// "name", "JS"
// "phone", "+91"

Note: for...in should not be used to iterate over an Array where the index order is important. According to Mozilla.

Iterating array with for…in (Not Recommended)

Array also be iterated using for..in loop but it’s best to use for..of for array

const array = ["JS", "Startup"];

for(const index in array){
  console.log(index, array[index]);
}

// "0", "JS"
// "1", "Startup"

Finally, I hope you like all the loops and know when to use which loop. Because as technology progress it’s better to keep in touch with it.

Check out our daily javascript quiz

  1. JavaScript Quiz – array map converts an element value with parseInt
  2. JS Quiz – does the splice method replace array element
  3. JS Quiz – is the console log function really override
  4. JavaScript Quiz – delete work on object create method object

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

Leave a Reply

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

Back to top
0 Shares
Share via
Copy link