Loops in JavaScript

Loops In JavaScript

Iterable data structures allow you to loop over them.

In simpler terms, Looping is a mechanism to go through each item in the list, run some code, then go to the next item.

Loops also have a base condition which tells when to stop looping through the list.

JavaScript has 2 methods for looping:

  1. for loop,
  2. while loop
for (let idx = 0; idx < 10; idx += 1) {
  console.log(idx)
}

let num = 0;
while (num < 10) {
  console.log({num})
  num += 1;
}

Loops In JavaScript

For Loops:

// C-styled for loop
// for (startPoint, endPoint, step) { //logic }
for (let idx = 0; idx < 10; idx += 1) {
  console.log(idx)
}


// for...of loop
const numArr = [1,2,3,4,5,6,7,8]
for (const num of numArr) {
  console.log(num)
}

There are multiple versions of for-loops in JavaScript:

  1. c-style for loop,
  2. for...of loop,
  3. for...in loop (later),
  4. for await ...of loop (later),

Loops In JavaScript

// C-styled for loop
for (let idx = 0; idx < 3; idx += 1) {
  console.log(idx)
}

// for (startPoint, endPoint, step) { //logic }
// for (startPoint, endPoint, step) { //logic }


let idx = 0; // start
console.log(idx) // logic, idx = 0
idx += 1 // step runs, idx = 1

idx < 3 // condition is checked, idx = 1, hence < 3, code moves forward

console.log(idx) // logic, idx = 1
idx += 1 // step runs, idx = 2

idx < 3// condition is checked, idx = 2, hence < 3, code moves forward

console.log(idx) // logic, idx = 2
idx += 1// step runs, idx = 3

idx < 3// condition is checked, idx = 3, hence not < 3, 
// code will not moves forward.
// Loop ends

How the c-style for loop runs:
 

for (startPoint, endPoint, step) { }

for (initialisation; condition; afterthought) {}

initialisation: any valid JS statement, ex: let num = 0
-- called only once before the condition doesn't fail

condition: any conditional statement that is evaluated once every time before
excuting the loop code

afterthought: executed once every time after the loop code is run


initialization
  condition
  code - no continue or break
  afterthought
 
  condition
  code - no continue or break
  afterthought

  condition
  code - no continue or break
  afterthought

  condition xx fails xx
  loop ends, code breaks out of loop

Loops In JavaScript

// for...of loop
const numArr = [1,2,3]
for (const num of numArr) {
  console.log(num)
}

const num = numArr[0]
console.log(num) // 1

const num = numArr[1]
console.log(num) // 2

const num = numArr[2]
console.log(num) // 3

How the for...of loop runs:

You can use for...of loops only on iterable data structures.

But for c-styled for loop, you don't need an array or anything, you can just add a start, end condition and run it.

Loops In JavaScript

// 1. while loop
// evaluate condition
// execute code

let num = 0;
while (num < 3) {
  num++;
  console.log({num})
}
// 1, 2, 3

// 2. do…while loop
// execute code
// evaluate condition
//  — the statement is 
//  executed at least once

let num = 0;
do {
  num++;
  console.log({num})
} while (num < 3)
// 1, 2, 3

While Loops:

There are 2 versions of while-loops in JavaScript:

  1. while loop
  2. do...while loop

Loops In JavaScript

// 1. while loop
// evaluate condition execute code
let num = 0;
while (num < 0) {
  num+=1;
  console.log({num})
}
// nothing

// 2. do…while loop
// execute code evaluate condition
//  — the statement is executed at least once
let num = 0;
do {
  num+=1;
  console.log({num})
} while (num < 0)
// 1

While Loops:

difference between while loo and do...while loop.

Loops In JavaScript

// C-styled for loop
for (let idx = 0; idx < 10; idx += 1) {
  console.log(idx)
}

// for (startPoint, endPoint, step) { //logic }
// for (startPoint, endPoint, step) { //logic }

Loop keywords:

continue: looping will continue, the code after the "continue" will NOT be executed

break: looping stops altogether
return: same as break, only valid when loop is written inside of a function.

Loops In JavaScript

new Array()
new String()
new Map()
new Set()

// doesn't has [Symbol.iterator] 
// in prototype
new Object()

Built-In Iterable data structures in JavaScript:

  1. Array,
  2. Strings,
  3. Map,
  4. Set

Iterable:

  • any data structure that has a method called "[Symbol.iterator]".
  • It should be function.
  • The function must return an object.
  • The object must have a "next()" method defined on it.
  • Calling the "next()" should return an object exactly like
  • {value: "", done: false} or
    {value: "", done: true}

Loops In JavaScript

const range = {
  from: 0,
  to: 10,
  [Symbol.iterator]: function(){
    current: this.from,
    last: this.to,
    next: function(){
      if (this.current <= this.last) {
        return { done: false, value: this.current++ };
      } else {
        return { done: true };
      }
    }
  }
}

for (let num of range) {
  console.log(num); // 1, 2, 3, 4, 5
}

Iterable:

  • any data structure that has a method called "[Symbol.iterator]".
  • It should be function.
  • The function must return an object.
  • The object must have a "next()" method defined on it.
  • Calling the "next()" should return an object exactly like
  • {value: "", done: false} or
    {value: "", done: true}

Loops In JavaScript


const numArr = [1, 234_45, 89,75, 4e9]
const strArr = ["asd", "qwe", "ert", "asdasdzxczxc"]
const mixArr = ["first", "234_45", {first: "Web", last: "Masters"}, true]

Let's try some loops:

Write a for loop and log each element, starting from 0th index

Loops In JavaScript


const numArr = [1, 234_45, 89,75, 4e9]
const strArr = ["asd", "qwe", "ert", "asdasdzxczxc"]
const mixArr = ["first", "234_45", {first: "Web", last: "Masters"}, true]

Let's try some loops:

Write a for loop starting from last index, and store each element in a new array. Log the array.

Loops In JavaScript


const strArr = "asdasdzxczxc";

Let's try some loops:

Write a for-loop to reverse a string

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop to log every alternate element, starting from 0th index

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop to log every alternate element, starting from last index

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop to log every 4th element, starting from 0th index

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop to log every 4th element, starting from last index

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop, and log the current and its immediate next element

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop, and log the current and its immediate previous element

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop, and log the current, its immediate previous, and its immediate next element,

Put the elements in a new object, and push that object in an array.

Return that array at the end of the loop

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop and count frequency of each element in the array. Store the element and its frequency in an object.

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop to log every element, starting from middle of the array

Loops In JavaScript


const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's try some loops:

Write a for-loop:

  • Start from 0th index, log every element,
  • then go to next index, log all next elements,
  • continue till last element

Loops In JavaScript


const numArr1 = [1, 2, 3, 4, 5]
const numArr2 = [6, 7, 8, 9, 10, 11, 12]

Let's try some loops:

There are 2 different arrays, write a for-loop, that should log elements at the same index in both the arrays. The loop should run till the longer array's length.

Loops In JavaScript


const numArr1 = [1, 2, 3, 4, 5]
const numArr2 = [6, 7, 8, 9, 10, 11, 12]

Let's try some loops:

There are 2 different arrays, write a for-loop, that:

  1. starts from 0th index, on array one,
  2. matches all the elements of the array two,
  3. if any element matches, logs true, and continue to next element
  4. once all the elements are looped on array 2, go to next element in array 1, then continue from step 1.,