JavaScript Interview Question #48

What is the difference between for...of and for...in?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

for...of iterates over values produced by an iterable such as an array, string, map, or set. for...in iterates over enumerable string property keys of an object, including inherited enumerable properties unless they are filtered.

Detailed Explanation

for...of iterates over values produced by an iterable such as an array, string, map, or set. for...in iterates over enumerable string property keys of an object, including inherited enumerable properties unless they are filtered.

Use for...of for array values. Use Object.keys, Object.entries, or carefully controlled for...in logic when working with object properties.

Code Example

const technologies = ["C#", "JavaScript"];

for (const technology of technologies) {
    console.log(technology);
}

const user = { name: "Asif", city: "Multan" };

for (const key in user) {
    if (Object.hasOwn(user, key)) {
        console.log(key, user[key]);
    }
}