DEV Community

Whoissosick
Whoissosick

Posted on

Loops [JS]

The basic syntax for f "for" loop

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

How Does the For...of Loop Work, and When Should You Use It?

A for...of loop is used when you need to loop over values from an iterable. Examples of iterables would be arrays, and strings.

for (variable of iterable) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

In this first example we have an array of numbers and we want to loop over each number and log it to the console.

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

for (const num of numbers) {
  console.log(num);
}
Enter fullscreen mode Exit fullscreen mode

We have created a variable called num that will represent the current number in the array. For iteration 1, num will be 1, for iteration 2, num will be 2, and so on.

Here is another example where we have a string and we want to loop over each character and log it to the console.

const str = 'WalterWhite';

for (let char of str) {
  console.log(char);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a variable called char that will represent the current character in the string.

It is important to note that you can use let, or const when declaring the variable in a for...of loop.

If you are going to use const though, make sure that the value of the variable does not change inside the loop. If it does, you will get an error.

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

for (const num of numbers) {
  console.log(num);
  num = num + 1; // This will cause an error
}
Enter fullscreen mode Exit fullscreen mode

Let's take a look at one last example dealing with an array of objects.

const people = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Jim', age: 40 }
];

for (const person of people) {
  console.log(`${person.name} is ${person.age} years old`);
}
Enter fullscreen mode Exit fullscreen mode

for...of loops are really useful when you need to loop over values from an iterable like an array or a string.

What Is the For...in Loop, and When Should You Use It?

A for...in loop is best used when you need to loop over the properties of an object. This loop will iterate over all enumerable properties of an object, including inherited properties and non-numeric properties.

An inherited property is a property that is inherited from the object's prototype chain. A non-numeric property is a property that is not a number or a string that can be converted to a number.

const fruit = {
  name: 'apple',
  color: 'red',
  price: 0.99
};

for (const prop in fruit) {
  console.log(fruit[prop]);
}
Enter fullscreen mode Exit fullscreen mode

The prop variable represents the current property of the object. fruit[prop] is used to access the value of each property.

For the first iteration, prop will be name. For the second iteration, prop will be color, and so on.

The results logged to the console will be apple, red, and 0.99.

In this second example, we have a nested object and we want to loop over each property and log the value to the console.

const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA'
  }
};

function isObject(obj) {
  return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
}

for (const prop in person) {
  if (isObject(person[prop])) {
    for (const nestedProp in person[prop]) {
      console.log(person[prop][nestedProp]);
    }
  } else {
    console.log(person[prop]);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a custom function isObject that checks if the value is an object.

The Array.isArray method is used to check if the value is an array. By placing the logical NOT operator (!) in front of the method, we are checking if the value is not an array.

The reason why we can't just use typeof equals 'object' is because arrays are also considered objects in JavaScript. We want to exclude arrays from the check.

Also, due to a historical bug in JavaScript, typeof null returns 'object'. So we want to also exclude null values from the check.

If the condition is true, we nest another for...in loop that will loop over the properties of the nested object and log the value to the console.

The nestedProp variable represents the current property of the nested object.

What Is a While Loop, and How Does It Differ from the Do...while Loop?

while (condition) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

while loops are useful when you do not know how many times you need to run the block of code. Here is an example of using a while loop:

let counter = 0;
while(counter < 5) {
  console.log(counter);
  counter++;
}
Enter fullscreen mode Exit fullscreen mode

Another loop similar to the while loop would be the do...while loop. Here is the basic syntax:

do {
  // code block to be executed
} while (condition);
Enter fullscreen mode Exit fullscreen mode

One key difference between a do...while loop and a while loop is that the do...while loop will execute the block of code at least once before checking the condition.

If the condition is true, the block of code will continue to execute. If the condition is false, the block of code will stop executing.

let counter = 0;
do {
  console.log(counter);
  counter++;
} while (counter < 5); 
Enter fullscreen mode Exit fullscreen mode

In this example, we have a variable called counter that is initialized to 0. The do...while loop will log the value of counter to the console and then increment counter by 1. After executing the block of code, it checks if the value of counter is less than 5. If it is, the loop will continue to run. If not, the loop will stop.

What Are the Break and Continue Statements Used for in Loops?

A break statement is used to exit a loop early, while a continue statement is used to skip the current iteration of a loop and move to the next one.

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

The break statement is useful when you want to exit a loop early based on a certain condition. For example, if you are searching for a specific value in an array, you can use a break statement to exit the loop once you find the value.

Sometimes you may want to skip a particular iteration of a loop without exiting the loop entirely. This is where the continue statement comes in. Here is an example of using a continue statement in a for loop:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue;
  }
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

The output of this code will print the numbers 0, 1, 2, 3, 4, 6, 7, 8, and 9. The number 5 is skipped because of the continue statement.

Another thing you can do with both the break and continue statements is to use labels to specify which loop you want to break or continue.

This is useful when you have nested loops and you want to control the flow of the outer loop from within the inner loop.

outerLoop: for (let i = 0; i < 3; i++) {
  innerLoop: for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop;
    }
    console.log(`i: ${i}, j: ${j}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have an outer for loop labeled outerLoop and an inner for loop labeled innerLoop.

When i is equal to 1 and j is equal to 1, we use the break statement with the outerLoop label to exit the outer loop early. This will exit both the inner and outer loops.

The output of this code will log the following to the console:

"i: 0, j: 0"
"i: 0, j: 1"
"i: 0, j: 2"
"i: 1, j: 0"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)