Basics
JS For...Of/For...In
Iterating with For...Of and For...In
JavaScript for...of and for...in iterate iterables and objects, with use cases.
Introduction to Iteration in JavaScript
JavaScript provides multiple ways to iterate over data structures, with for...of and for...in being two of the most commonly used loops for different use cases. Understanding how each of these loops operates will help you choose the right one for your task.
The For...Of Loop
The for...of loop is used to iterate over iterable objects, such as Arrays, Strings, Maps, and Sets. It allows you to access the values directly, making it a preferred choice when you only need to work with the values of an iterable.
In the example above, the for...of
loop iterates over each element in the fruits
array, logging each fruit name to the console.
The For...In Loop
The for...in loop is used for iterating over the enumerable properties of an object. It provides access to the keys, making it ideal for looping through objects to access both key and value pairs.
In this example, the for...in
loop iterates over the car
object's properties, allowing us to log both the property names and their corresponding values.
Key Differences and Use Cases
While both loops are essential for iteration, they serve different purposes:
- for...of is optimal for iterating over iterables like arrays and strings where you need direct access to the values.
- for...in is best for iterating over objects where you need to work with keys and values.
Choosing the correct loop depends on the data structure you are working with and the specific requirement of your task.
Conclusion
The for...of and for...in loops are powerful tools in JavaScript for data iteration. By understanding their differences and use cases, you can write cleaner and more efficient code. Always choose the loop that best fits the structure of the data you are working with.
Basics
- Introduction
- Where To
- Output
- Syntax
- Comments
- Variables
- Scope
- Hoisting
- Errors
- Data Types
- Operators
- Ternary Operator
- Short-Circuit Evaluation
- If Else
- Switch
- Loops
- For...Of/For...In
- Functions
- this Keyword
- Objects
- Arrays
- Strings
- Template Literals
- Numbers
- Number Properties
- Dates
- Math
- Booleans
- Type Conversion
- Destructuring
- Spread/Rest
- RegExp
- Strict Mode
- Modules
- Security Basics
- Debugging
- Best Practices
- Mistakes
- Performance
- Reserved Words
- Sets
- Maps
- Bitwise
- Array Const