JavaScript Tips on Objects and Array and their For loop

This is JavaScript Tips on Objects and Array and their For loop.

In JavaScript, there is an Object and represented as:


var someObj = {name:"YongHao", age:25}

There is an Array and represented as:


var someArr = [1,2,3,4]

Use normal for loop only for Array, and use for…in only for Object.

For example, for Object

var someObj = {name:"YongHao", age:25}
for(var i in someObj) {
  console.log(i + ' - ' + someObj[i]);
}

We get:
name – YongHao
age – 25

For Array

var someArr = [1,2,3,4]
for(var i = 0; i < someArr.length; i++) {
  console.log(i + ' - ' + someArr[i]);
}

We get:
0 - 1
1 - 2
2 - 3
3 - 4

Do not use for...in to Array, if you do:

var someArr = [1,2,3,4]
for(var i in someArr) {
  console.log(i + ' - ' + someArr[i]);
}

It may return good result, but not recommended, as i now is a string but not an integer.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.