
JavaScript에서 반복문을 사용할 때, for 루프 안에 in을 써야 할지 of를 써야 할지 헷갈린 적이 많다.
이 두 키워드는 언뜻 비슷해 보이지만, 사실 순회하는 대상 자체가 완전히 다르다.
const myObject = { name: 'Alice', age: 25, job: 'Developer' };
// 객체를 순회할 때
for (const key in myObject) {
// key: 'name', 'age', 'job'
console.log(`키: ${key}, 값: ${myObject[key]}`);
// 출력: 키: name, 값: Alice
}
// 배열에 사용 (인덱스를 문자열로 가져옵니다)
const myArray = ['A', 'B', 'C'];
for (const index in myArray) {
// index: '0', '1', '2' (문자열 인덱스)
console.log(`인덱스: ${index}, 값: ${myArray[index]}`);
// 출력: 인덱스: 0, 값: A
}
// 배열을 순회할 때 (배열의 값 자체를 가져옴)
const myArray = ['apple', 'banana', 'cherry'];
for (const value of myArray) {
// value: 'apple', 'banana', 'cherry' (값을 가져옴)
console.log(value);
// 출력: apple
}
// 문자열을 순회할 때
const myString = 'Hello';
for (const char of myString) {
// char: 'H', 'e', 'l', 'l', 'o'
console.log(char);
// 출력: H
}