Mukund Kumar Mukund Kumar - 1 year ago 67
Javascript Question

What is the difference between ( for... in ) and ( for... of ) in javascript?

I know what is

for... in
loop(it iterate over key), but heard first time about
for... of
(it iterate over value). I am confused with
for... of
loop. I didn't get adject. This is the code below :

var arr = [3, 5, 7]; = "hello";

for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"

for (var i of arr) {
console.log(i); // logs "3", "5", "7"
//it is does not log "3", "5", "7","hello"

What I got is, for... of iterates over property values. then why it doesn't log(return)
"3", "5", "7","hello"
instead of
"3", "5", "7"
? but
for... in
loop iterate over each key ("0", "1", "2", "foo"). here
for... in
loop also iterate over
key. but for... of not iterarte over value of
property ie
.Why it is like that?

Long story in short:

here i console
for... of
loop. it should be log
"3", "5", "7","hello"
but here it logs
"3", "5", "7"
. Why ?

Example Link

Answer Source

for in loops over enumerable property names of an object.

for of (new in ES6) does use an object-specific iterator and loop over the values generated by that.

In your example, the array iterator does yield all the values in the array (ignoring non-index properties).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download