DEV Community

Nitin Sharma
Nitin Sharma

Posted on

JavaScript Array Iteration, a curious case!

var box = [];
box['size'] = 9;
box['0'] = 'Cool';
box.push = 'coffee';
for(var i=0 ; i<box.length ; i++){
console.log(box[i]); // ???
}

What could be the console.log output here?

Top comments (1)

Collapse
 
asuddle profile image
Asuddle

The output will be Cool, and the length of the array will be 1

Explanation

box['size'] = 9;

we cannot set index of array as string ,if we set a index as string, we are actually setting a property of the object for e.g, these 2 things are equal

arr.a = 'abc';
arr['a'] = 'abc';

box.push = 'coffee';;
it is not the right syntax for pushing array
box.push('coffee')
with the statement written in question , it too refers to setting the property of object

if you return box['size'] , it will give 9 but it wont be shown in the box array , same is the case with box.push = 'coffee';