Blog

Multiple Ways to Use For Loops with Arrays and Object Literals in JavaScript
Posted on July 6, 2015 in JavaScript by Matt Jennings

For Loop that Uses the Index of an Array

var myArr = [1, 4, -9, -5, 5, 2];

for(index in myArr) {
  console.log(myArr[index]);
}

/*
Displays:
1
4
-9
-5
5
2
*/

Iterate through an Object Literal Using a For-In Loop

// The object key names must be unique ("name1", "name2")
// to be looped through
var peopleObj = {name1: "Brandi", name2: "Mia"};

// "value" is the value
for(value in peopleObj) {

  console.log(peopleObj[value]);

}

/*
Output:
Brandi
Mia
*/

Leave a Reply