Javascript  

 

 

 

 

 

Loops

 

There are many different ways to implement a function in Javascript. It gives a wide range of flexibility but sometimes it is confusing and make it difficult to read code if you are not familiar with all those different ways of implimentation.

for

The for loop is one of the most commonly used loops in JavaScript. It allows you to repeat a block of code a set number of times, and it's particularly useful when you know exactly how many times you want to iterate. The syntax of a for loop consists of three important parts: initialization, condition, and final expression, all included in parentheses after the for keyword, and followed by the block of code to execute.

Syntax:

for (initialization; condition; final expression) {

  // Block of code to be executed

}

  • Initialization: Typically used to define and set up your loop variable.
  • Condition: The loop will continue to execute as long as this condition evaluates to true.
  • Final Expression: Executed at the end of each loop iteration, often used to increment or decrement the loop counter.

Example 1: Basic for Loop

Printing numbers from 0 to 4:

for (let i = 0; i < 5; i++) {

  console.log(i);

}

Example 2: Iterating Over an Array

Looping through an array and logging each element:

const fruits = ['Apple', 'Banana', 'Cherry'];

 

for (let i = 0; i < fruits.length; i++) {

  console.log(fruits[i]);

}

Example 3: Nested for Loops

Using nested for loops to work with multi-dimensional arrays or to create patterns:

for (let i = 0; i < 3; i++) {

  for (let j = 0; j < 2; j++) {

    console.log(`i = ${i}, j = ${j}`);

  }

}

Example 4: Using for Loop for HTML Manipulation

Dynamically creating a list in HTML using a for loop:

<ul id="fruitList"></ul>

 

<script>

const fruits = ['Apple', 'Banana', 'Cherry'];

const list = document.getElementById('fruitList');

 

for (let i = 0; i < fruits.length; i++) {

  const listItem = document.createElement('li');

  listItem.textContent = fruits[i];

  list.appendChild(listItem);

}

</script>

Example 5: Breaking Out of a Loop

You can use the break statement to exit a loop before the condition becomes false:

for (let i = 0; i < 10; i++) {

  if (i === 5) {

    break; // Exits the loop when i is 5

  }

  console.log(i);

}

Example 6: Skipping Iterations with continue

The continue statement can be used to skip the rest of the code inside the loop for the current iteration:

for (let i = 0; i < 5; i++) {

  if (i === 2) {

    continue; // Skips the rest of the loop when i is 2

  }

  console.log(i);

}

for..in

The for...in statement in JavaScript is used to iterate over all enumerable properties of an object. This includes iterating over the object's own properties as well as those which are inherited through the prototype chain. It's particularly useful for iterating over object properties without knowing the keys in advance.

Syntax:

for (variable in object) {

  // statements

}

  • variable: A different property name is assigned to this variable on each iteration.
  • object: The object whose non-Symbol enumerable properties are iterated over.

Characteristics:

  • Iterates over the enumerable properties of an object.
  • The order of iteration is not guaranteed to be in any specific order. It can vary across different JavaScript engines.
  • Enumerates properties in the prototype chain as well.

Example 1: Basic Usage

Iterating over the properties of an object and logging the key-value pairs:

const person = {

  name: 'Alice',

  age: 25,

  occupation: 'Developer'

};

 

for (const key in person) {

  console.log(`${key}: ${person[key]}`);

}

 

Expected Output :----------------------

name: Alice

age: 25

occupation: Developer

Example 2: Filtering Own Properties

Using Object.hasOwnProperty() to ensure that only the object’s own properties are iterated over, excluding properties that are inherited through the prototype chain:

const person = {

  name: 'Alice',

  age: 25,

  occupation: 'Developer'

};

 

for (const key in person) {

  if (person.hasOwnProperty(key)) {

    console.log(`${key}: ${person[key]}`);

  }

}

 

Expected Output :----------------------

name: Alice

age: 25

occupation: Developer

This output is the same as the first example because the person object does not inherit any enumerable properties. The use of hasOwnProperty() ensures that if the object had inherited properties, they would not be logged.

Example 3: Iterating Over Array Indices

Here's why using for...in for array iteration is not recommended, but if used, it would work as follows:

const array = ['a', 'b', 'c'];

 

for (const index in array) {

  console.log(`${index}: ${array[index]}`);

}

 

Expected Output :----------------------

0: a

1: b

2: c

While this gives the expected result, using for...in for arrays is not recommended because it iterates over all enumerable properties, not just numeric indices, and may include inherited properties. Additionally, the order of iteration is not guaranteed, which is important for arrays.

for...of

The for...of statement in JavaScript creates a loop iterating over iterable objects, including: arrays, strings, maps, sets, and more. It allows you to loop directly over the values of the iterable, not the keys like the for...in loop. This loop is particularly useful for iterating over collections where you're interested in the values rather than the properties.s

Syntax:

for (variable of iterable) {

  // statements

}

  • variable: On each iteration, the value of the next property is assigned to this variable.
  • iterable: An object that has iterable properties.

Characteristics:

  • Directly accesses the values of an iterable collection.
  • Simpler and cleaner syntax for iteration compared to traditional for loops.
  • Does not iterate over object properties, as objects are not directly iterable in JavaScript.

Example 1: Iterating over an Array

const fruits = ['apple', 'banana', 'cherry'];

 

for (const fruit of fruits) {

  console.log(fruit);

}

 

Expected Output :----------------------

apple

banana

cherry

Example 2: Iterating over a String

const greeting = 'Hello';

 

for (const char of greeting) {

  console.log(char);

}

 

Expected Output :----------------------

H

e

l

l

o

Example 3: Iterating over a Map

const map = new Map();

map.set('a', 1);

map.set('b', 2);

 

for (const [key, value] of map) {

  console.log(`${key}: ${value}`);

}

 

Expected Output :----------------------

a: 1

b: 2

Example 4: Iterating over a Set

const set = new Set([1, 2, 3]);

 

for (const value of set) {

  console.log(value);

}

 

Expected Output :----------------------

1

2

3

Example 5: Using for...of with break

const numbers = [1, 2, 3, 4, 5];

 

for (const number of numbers) {

  if (number > 3) break;

  console.log(number);

}

 

Expected Output :----------------------

1

2

3

while

The while loop in JavaScript executes its statements as long as a specified condition evaluates to true. It's a part of JavaScript's standard control structures and provides a straightforward way to execute a block of code multiple times.

Syntax:

while (condition) {

  // Block of code to be executed

}

  • condition: Before each loop iteration, this condition is evaluated. If the condition evaluates to true, the code within the block is executed. This process repeats until the condition evaluates to false.

Characteristics:

The condition is checked before the execution of the loop's code block. If the condition is false from the beginning, the code block may never run.

The condition must eventually become false; otherwise, the loop will create an infinite loop, potentially crashing your program or browser.

Ideal for situations where the number of iterations is not known before the loop starts.

Example 1: Basic while Loop

let i = 0;

while (i < 5) {

  console.log(i);

  i++;

}

 

Expected Output :----------------------

0

1

2

3

4

Example 2: Using while Loop for User Input Validation

This example simulates validating user input until a correct value is provided. Here, it's simplified to incrementing i until it reaches 5.

let i = 0;

 

// Simulate a condition that must be met (e.g., valid user input)

while (i !== 5) {

  i = Math.floor(Math.random() * 10);  // Simulating user input

  console.log(`Trying ${i}`);

}

 

console.log('Valid input received.');

 

Expected Output :----------------------

Various "Trying X" messages until it logs "Trying 5" followed by "Valid input received." The exact output will vary due to the use of Math.random().

Example 3: Avoiding Infinite Loops

Ensure the loop's condition is properly managed to avoid an infinite loop:

let i = 0;

 

while (i < 5) {

  console.log(i);

  // Forgot to increment i, which would cause an infinite loop

}

 

console.log('Valid input received.');

To prevent the program from hanging or crashing, it's crucial to modify the loop variable (i) or condition within the loop.

Usage Tips:

Always ensure that the loop has a well-defined exit condition to prevent infinite loops.

Consider using other loop types (for, for...of, do...while) if they better fit your use case, especially when dealing with known iterable sequences or when you need the code to run at least once.

do...while

The do...while loop is a variant of the loop structure in JavaScript that ensures the loop's body is executed at least once before the condition is tested. This behavior is because the loop's condition is checked at the end of the loop's body, not at the beginning like the while loop.

Syntax:

do {

  // Block of code to be executed

} while (condition);

  • Block of code: This is executed at least once and then repeatedly as long as the condition evaluates to true.
  • condition: This is evaluated after the block of code has been executed. If this condition evaluates to true, the block of code is executed again.

Characteristics:

  • The code block within a do...while loop will always run at least once, even if the condition is false on the first iteration.
  • Like the while loop, the condition must eventually become false to avoid creating an infinite loop.

Example 1: Basic do...while Loop

let i = 0;

 

do {

  console.log(i);

  i++;

} while (i < 5);

 

Expected Output :----------------------

0

1

2

3

4

Example 2: do...while with Initially False Condition

Even if the condition is false from the start, the code block is executed once:

let i = 5;

 

do {

  console.log(`i is ${i}`);

} while (i < 5);

 

Expected Output :----------------------

i is 5

Example 3: User Input Validation

A do...while loop can be useful for scenarios like validating user input where you need to prompt the user at least once and then repeat until a valid input is provided:

let input;

 

do {

  // Simulate input with random number for demonstration purposes

  input = Math.floor(Math.random() * 10);

  console.log(`You entered: ${input}`);

} while (input !== 5);

 

console.log('Valid input received.');

 

Expected Output :----------------------

Multiple "You entered: X" messages until it logs "You entered: 5" followed by "Valid input received." The exact output will vary due to the use of Math.random()

Usage Tips:

  • Use do...while loops when you need to ensure the loop's body is executed at least once, regardless of whether the condition is initially true.
  • Be mindful of the loop's condition to prevent infinite loops, ensuring that it eventually evaluates to false.