JS Input/Output Solution 3
What value will be displayed in the console?
1
2
3
4
5
6
7
8
var arr = [];
arr[0] = 'a';
arr[1] = 'b';
arr.foo = 'c';
console.log(arr); // ?
console.log(arr.foo); // ?
console.log(arr.length); // ?
Solution:
1
2
3
4
5
6
7
8
var arr = [];
arr[0] = 'a';
arr[1] = 'b';
arr.foo = 'c';
console.log(arr); // ['a', 'b', foo: 'c'];
console.log(arr.foo); // 'c'
console.log(arr.length); // 2
Arrays
in JavaScript are objects
plus a few methods and properties(length
). That is why they can have object properties.
But those are not considered as part of the actual array.
Therefore, in this example -
arr
is equal to ['a', 'b', foo: 'c']
But, arr.length
is 2 and not 3 because length
property only tracks the highest numeric index within an array. It doesn’t loop over an array to count the number of elements.