Module 5 · Lesson 2 of 418/32 in the course~16 min
Module lessons (2/4)
for…of and for…in
Lesson preview5 hands-on exercises readyJavaScript Course · Module 5 — Control flow
Iterate values of a collection vs keys of an object. When to use which.
What you'll learn in this lesson
- Choose confidently between
for...of(iterable values) andfor...in(enumerable keys). - Avoid the classic mistake of using
for...inon arrays by getting index strings ('0','1'). - Protect against inherited prototype chain properties with
Object.hasOwnorObject.keys. - Use
.entries()to get index+value in loops on arrays and key+value pairs on objects.
Overview
The confusion between for...of and for...in is one of the most frequent errors in JavaScript: the two constructs have almost identical syntax but cross opposite dimensions (values of an iterable vs keys of an object).
Sections covered in this lesson
- 1Mental model: values (
of) vs keys (in) - 2Progressive examples
- 3Guided laboratory
- 4Check for understanding
Pro Lesson · Module 5 — Control flow
Unlock "for…of and for…in" and the full JavaScript Course curriculum
Iterate values of a collection vs keys of an object. When to use which.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in JavaScript Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.