Last active
December 31, 2021 16:45
-
-
Save Alonso-Pablo/fa7ce82a5c8a16eb27ec7be75c864e1c to your computer and use it in GitHub Desktop.
Diff. between 'For of' and 'For in'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const obj = { a: 1, b: 2, c: 3 }; | |
const array = ['a', 'b', 'c'] | |
const str = 'abc' | |
// FOR OF OBJECT | |
for (const property of obj) { | |
console.log(property); | |
} | |
// Output: | |
// TypeError: object is not iterable | |
// FOR IN OBJECT | |
for (const property in obj) { | |
console.log(property); | |
} | |
// Output: | |
// 'a' | |
// 'b' | |
// 'c' | |
// FOR OF ARRAY | |
for (const item of arr) { | |
console.log(item); | |
} | |
// Output: | |
// 'a' | |
// 'b' | |
// 'c' | |
// FOR IN ARRAY | |
for (const index in arr) { | |
console.log(index); | |
} | |
// Output: | |
// '0' | |
// '1' | |
// '2' | |
// FOR OF STRING | |
for (const char of str) { | |
console.log(char); | |
} | |
// Output: | |
// 'a' | |
// 'b' | |
// 'c' | |
// FOR IN STRING | |
for (const index in str) { | |
console.log(index); | |
} | |
// Output: | |
// '0' | |
// '1' | |
// '2' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment