Iteration

단단한어린이·2023년 1월 22일
0

Javascript

목록 보기
17/17
post-thumbnail

Iteration in JavaScript refers to the process of repeatedly executing a block of code until a certain condition is met. One of the most common ways to iterate in JavaScript is by using a for loop. A for loop consists of a starting point, an ending point, and a way to increment or decrement the loop counter. Here's an example of a simple for loop that counts from 1 to 10:

Copy code
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Another way to iterate in JavaScript is by using the forEach() method, which is available on arrays. The forEach() method takes a callback function as an argument, and it will execute that function once for each element in the array. Here's an example of how to use the forEach() method to print out all the elements in an array:

let myArray = [1, 2, 3, 4, 5];
myArray.forEach(function(element) {
  console.log(element);
});

ES6 introduced a new way of iteration using for-of loop which is used to iterate over any iterable like arrays, strings, maps, sets and more.

let myArray = [1, 2, 3, 4, 5];
for (let element of myArray) {
  console.log(element);
}

Another way to iterate in JavaScript is by using the map() method, which is also available on arrays. The map() method takes a callback function as an argument, and it will execute that function once for each element in the array, and then it returns a new array with the results. Here's an example of how to use the map() method to double the value of each element in an array:

let myArray = [1, 2, 3, 4, 5];
let doubledArray = myArray.map(function(element) {
  return element * 2;
});
console.log(doubledArray);

Finally, JavaScript also provides the for-in loop which is used to iterate over properties of an object.

let person = {name:'John', age:30, job:'teacher'};
for (let key in person) {
  console.log(key + ':' + person[key]);
}

In conclusion, there are many ways to iterate in JavaScript, and the appropriate method depends on the specific use case. The for loop, forEach(), for-of, map(), and for-in are some of the most commonly used methods for iteration in JavaScript.

profile
Footprints in Coding

0개의 댓글