JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is the difference between for…in and for…of variables?

Asked on Jul 28, 2024

Answer

The "for...in" loop iterates over the enumerable properties of an object, while the "for...of" loop iterates over the values of iterable objects like arrays, strings, and more.
// Example of for...in
        const obj = { a: 1, b: 2, c: 3 };
        for (const key in obj) {
            console.log(key); // Outputs: "a", "b", "c"
        }

        // Example of for...of
        const array = [10, 20, 30];
        for (const value of array) {
            console.log(value); // Outputs: 10, 20, 30
        }
Additional Comment:
  • "for...in" is used for iterating over object properties.
  • "for...of" is used for iterating over iterable objects like arrays, strings, Maps, Sets, etc.
  • "for...in" returns keys (property names), while "for...of" returns values.
  • Use "for...in" when you need to work with object properties, and "for...of" when you need to work with values of an iterable.
✅ Answered with JavaScript best practices.
← Back to All Questions