Loops in Javascript

Quick Note: If you don’t understand anything or have any questions or just want to talk about tech, you can connect with me on Instagram, Facebook or twitter

1. Loops in Javascript

for — loops through a block of code a number of times

for/in — loops through key value of an objext

let person = {fname:"John", lname:"Doe", age:25};
let x = 0
let text = ''
for (x in person) {
text += person[x] + " ";
}
console.log(txt) //John Doe 25

while — loops through a block of code while a specified condition is true

while (let i < 10) {
text += "The number is " + i;
i++;
}

do/while — also loops through a block of code while a specified condition is true

do {
text += "The number is " + i;
i++;
}
while (i < 10);

ForEach Loop — Executes a provided function once for each array element.

Before (without forEach)

const items = ['item1', 'item2', 'item3']; 
const copy = [];
for (let i=0; i<items.length; i++) { 
copy.push(items[i])
}
console.log(copy) ["item1", "item2", "item3"]

After (with forEach)

const items = ['item1', 'item2', 'item3']; 
const copy = [];
items.forEach(function(item){ 
copy.push(item)
});

More Information

Important/Interesting Question about forEach: Click Here

for…of -

for…of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set

Iterating over an ArraySection

let iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31

Iterating over a String

let iterable = 'boo';
for (let value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"

More Information