for...in과 for...of 루프의 차이점
두 루프 모두 무언가를 반복(iterate)한다는 공통점이 있지만, 가장 큰 차이점은 무엇을 순회하느냐에 있습니다.
1) for...in 루프
for...in 루프는 객체의 열거 가능한 속성(enumerable properties)을 임의의 순서로 순회합니다. 이 루프는 값(value)이 아니라 오직 속성(key)에만 관심을 둡니다.
다음 예제에서는 for...in 루프를 사용해 배열의 속성을 순회합니다. 배열에서 인덱스(index)는 중요한 속성이므로 각 요소의 인덱스가 순서대로 출력됩니다. 그런데 인덱스뿐만 아니라 "inherProp2", "inherProp1"처럼 상속된 속성(inherited properties)까지 함께 출력되는 점에 주목하세요.
예제 1
<html>
<body>
<script>
Object.prototype.inherProp1 = function() {};
Array.prototype.inherProp2= function() {};
var org = ["Apple", "Microsoft", "Tesla"]
org.anotherOrg = "solarCity";
for (var key in org) {
document.write(key);
document.write("</br>");
}
</script>
</body>
</html>
출력 결과
0 1 2 anotherOrg // 자체 속성(own property) inherProp2 // 상속된 속성(inherited property) inherProp1 // 상속된 속성(inherited property)
다음 예제에서는 hasOwnProperty() 메서드를 사용했기 때문에 인덱스 및 기타 자체 속성만 출력되고, "inherProp1"과 "inherProp2" 같은 상속된 속성은 제외됩니다.
예제 2
<html>
<body>
<script>
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
var org = ["Apple", "Microsoft", "Tesla"]
org.anotherOrg = "solarCity";
for (var i in org) {
if (org.hasOwnProperty(i)) {
document.write(i);
document.write("</br>");
}
}
</script>
</body>
</html>
출력 결과
0 1 2 anotherOrg
2) for...of 루프
for...in 루프와 달리, for...of 루프는 객체가 순회 가능하다고 정의한 값(values)을 직접 순회합니다.
다음 예제에서는 for...of 루프를 사용하여 'Apple', 'Microsoft', 'Tesla'라는 실제 요소 값들이 그대로 출력됩니다.
예제
<html>
<body>
<script>
var org = ["Apple", "Microsoft", "Tesla"]
for (var key of org) {
document.write(key);
document.write("</br>");
}
</script>
</body>
</html>
출력 결과
Apple Microsoft Tesla
정리
for...in은 객체의 키(속성 이름)를 순회하며, 상속된 속성까지 포함될 수 있으므로 필요하다면 hasOwnProperty()로 필터링하는 것이 안전합니다. 반면 for...of는 배열, 문자열, Map, Set 등 이터러블(iterable) 객체의 값을 순회하며, 일반 객체에는 사용할 수 없습니다. 따라서 키가 필요하면 for...in(또는 Object.keys), 값이 필요하면 for...of를 사용하는 것이 바람직합니다.