2ality에서 포스팅을 읽으며 번역, 정리한 글입니다.
Looping over Arrays: `for` vs. `for-in` vs. `.forEach()` vs. `for-of`
Book, exercises, quizzes (free to read online)
2ality.com
자바스크립트에서 제공하는 배열 반복 구문 4가지에 대해서 비교해보려고 한다.
const array = [1, 2, 3, 4, 5, 6, 7];
// ES1 for 구문
for (let index = 0; index < array.length; index++) {
console.log(index, array[index]);
}
// ES1 for in 구문
for (const key in array) {
console.log(key);
}
// ES5 forEach 구문
array.forEach((item, index) => console.log(index, item));
// ES6 for of 구문
for (const item of array) {
console.log(item);
}
1. for loop [ES1]
ECMAScript1에서 정의된 for 구문은 배열의 index와 value를 순회한다.
구문이 다소 번거롭기는 하지만, 배열을 순회할 때 시작점을 지정할 수 있다는 점은 매우 유용하다.
const array = [1, 2, 3, 4, 5, 6, 7];
// ES1 for 구문
for (let index = 0; index < array.length; index++) {
console.log(index, array[index]);
}
// output
// 0 1
// 1 2
// 2 3
// 3 4
// 5 6
// 6 7
2. for-in loop [ES1]
마찬가지로 ECMAScript1에서 정의되었다. for-in은 배열의 키를 순회한다.
for-in은 아래와 같은 특징을 갖는다.
const array = [1, 2, 3, 4, 5, 6, 7];
array.props = 'hello';
for (const key in array) {
console.log(key);
}
// output
// '0'
// '1'
// '2'
// '3'
// '4'
// '5'
// '6'
// 'hello'
- value가 아닌 key를 순회한다.
- 배열 원소의 key는 Number 타입이 아닌 String 타입이다.
- 배열 원소 뿐만 아니라 열거형 프로퍼티 키도 순회할 수 있다.
3. .forEach() [ES5]
ECMAScript5에서 소개된 Helper Method이다.
const array = [1, 2, 3, 4, 5, 6, 7];
// ES5 forEach 구문
array.forEach((item, index) => console.log(index, item));
// output
// 0 1
// 1 2
// 2 3
// 3 4
// 5 6
// 6 7
forEach는 굉장히 편리하고, ES6에서 도입된 화살표 함수 구문과도 함께 사용할 수 있다.
다만 아래와 같은 단점이 있다.
- 본문에서 await과 함께 사용할 수 없다.
- break를 사용해서 중도에 멈출 수 없다.
아래 예시를 살펴보자.
const array = [1, 2, 3, 4, 5, 6, 7];
// ES5 forEach 구문
array.forEach((item, index) => {
if (index > 3) {
return true; // break
}
console.log(index, item);
// callback은 암묵적으로 falsy value인 `undefined`를 반환한다. 즉, 순회는 계속되고 있다.
});
// output : 마치 `return true`에서 순회가 종료된 것처럼 보인다.
// 0 1
// 1 2
// 2 3
// 3 4
4. for-of loop [ES6]
for-of는 ECMAScript6에서 추가되었다.
const array = [1, 2, 3, 4, 5, 6, 7];
for (const item of array) {
console.log(item);
}
// output
// 0 1
// 1 2
// 2 3
// 3 4
// 5 6
// 6 7
for-of는 아래와 같은 특징을 갖는다.
- 배열을 순회한다.
- await과 함께 사용할 수 있다.
- break, continue를 사용할 수 있다.
- 배열을 포함한 iterable 객체라면 for-of를 사용할 수 있다. (예. generator, Map, Set...)
- key, Entries를 사용해서 key, value에 접근할 수 있다.