Menu
Posted At Fri, Mar 22, 2024 9:47 PM

JavaScript Loops and Iterations

Listen | 2 min read

Table of Contents:

  1. Introduction
  2. Loops in JavaScript
  3. Iterations in JavaScript
    • isLooselyEqual
    • isStrictlyEqual
    • SameValueZero
    • SameValue

1. Introduction

In JavaScript, loops and iterations are fundamental constructs used for repetitive tasks and data manipulation. Loops allow executing a block of code repeatedly, while iterations refer to the process of accessing and processing each element in a data structure or collection. In this article, we will delve into different aspects of loops and iterations in JavaScript, focusing on various methods for comparison such as isLooselyEqual, isStrictlyEqual, SameValueZero, and SameValue.

2. Loops in JavaScript

JavaScript provides several types of loops for different use cases:

  • for Loop: Executes a block of code a specified number of times.

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

  • while Loop: Executes a block of code as long as a specified condition is true.

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

  • do...while Loop: Similar to a while loop, but the block of code is executed at least once, even if the condition is false.

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

  • for...in Loop: Iterates over the enumerable properties of an object.

const person = { name: 'John', age: 30 };
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

  • for...of Loop: Iterates over iterable objects like arrays, strings, maps, sets, etc.

const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
  console.log(fruit);
}

3. Iterations in JavaScript

Iterations involve comparing values or elements in JavaScript. Let's explore some common methods:

  • isLooselyEqual: Checks if two values are equal in JavaScript, allowing type coercion.

console.log(2 == '2'); // true
console.log(2 == 2);   // true
console.log(2 == '3'); // false

  • isStrictlyEqual: Compares two values in JavaScript without type coercion.

console.log(2 === '2'); // false
console.log(2 === 2);   // true
console.log(2 === '3'); // false

  • SameValueZero: Determines whether two values are the same, considering +0 and -0 to be equal.

console.log(Object.is(+0, -0)); // false
console.log(Object.is(NaN, NaN)); // true

  • SameValue: Compares two values for equality, similar to === but with some differences regarding NaN and signed zeroes.

console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0, -0)); // false

These methods provide different ways to compare values in JavaScript, each with its specific use cases and behaviors.

1258 1

Comments