Various loops available in javascript

· 283 words · 2 minute read

This post will focus on the various loops available in the javascript and when to use them.

  1. for - Probably the most commonly used loop in any programming language. The for loop runs until a specific condition is true. As seen below, it has 3 parts:

i) initialization (i=0)
ii) condition (i<5)
iii) increment/decrement (i++/i--)

for (let i = 0; i < 5; i++) {
  console.log(i);
}
for (let i = 5; i >= 0; i--) {
  console.log(i);
}
  1. while - While loop continues to run as long as the condition is true. The syntax is as follows. If there is no change in condition, then the loop will run infinitely.
while (condition) {
  // do something
}
  1. for…in - for…in loop is useful to iterate over an object. It returns the properties defined in that object.
const obj = {
  id: 1,
  location: "Melb",
  available: true,
};

for (let o in obj) {
  console.log(o);
}

// output
// id
// location
// available

The values associated with properties can be accessed as follows.

const obj = {
  id: 1,
  location: "Melb",
  available: true,
};

for (const o in obj) {
  console.log(o, obj[o]);
}

// output
// id 1
// location Melb
// available true
  1. . for…of - for…of loop is useful to iterate over an iterable object. It returns the properties defined in it. Iterable object can be anything that can looped be through, for ex, Array, Map, Set and even String is iterable object
const str = "sample";

for (const s of str) {
  console.log(s);
}

/*
s
a
m
p
l
e
*/

Note: Trying to use for…of with an object will result in

Uncaught TypeError: obj is not iterable