Skip to content

Instantly share code, notes, and snippets.

@alik472
Last active May 15, 2019 14:07
Show Gist options
  • Save alik472/d1899bc43f36b8e723e4abf7390ba5bd to your computer and use it in GitHub Desktop.
Save alik472/d1899bc43f36b8e723e4abf7390ba5bd to your computer and use it in GitHub Desktop.
JS Days - Part 4 - for loops (for of/ for in/ forEach)
var myobj=['a','b','c']
for (var x in myobj){console.log(x)}
// 0
// 1
// 2
for (var x of myobj){console.log(x)}
// a
// b
// c
var myobj2={'name':'ali',age:19}
for (var x in myobj2){console.log(x)}
// name
// age
for (var x of myobj2){console.log(x)}
// Uncaught TypeError: myobj2 is not iterable
// In JavaScript, Objects are not iterable unless they implement the iterable protocol. Instead you have to use Object.keys or Object.entries, to iterate over the properties or entries of an object.
for (var x of Object.keys(myobj2)){console.log(x)}
// name
// age
for (var x of Object.entries(myobj2)){console.log(x)}
// ["name", "ali"]
// ["age", 19]
myobj2.forEach(x,y => {console.log(x)})
// TypeError: myobj2.forEach is not a function
// Object does not have forEach, it belongs to Array prototype
var keys=Object.keys(myobj2)
console.log(keys)
//[ 'name', 'age' ]
var values=Object.values(myobj2)
console.log(values)
//[ 'ali', 19 ]
var entries = Object.entries(myobj2)
console.log(entries)
//[ [ 'name', 'ali' ], [ 'age', 19 ] ]
myobj.forEach(item=>{
console.log(item)
})
// a
// b
// c
myobj.forEach((item,index,array)=>{
console.log(item,index,array)
})
// a 0 [ 'a', 'b', 'c' ]
// b 1 [ 'a', 'b', 'c' ]
// c 2 [ 'a', 'b', 'c' ]
myobj.forEach((item,index)=>{
console.log(index)
})
// 0
// 1
// 2
console.log(myobj.toString())
// a,b,c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment