javascript interview question #49

Will the length of the JS array change? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

All JavaScript arrays have the push function. It’s used to add new elements to the array:

const arr = [ 1, 2 ];

arr.push(3);   // [ 1, 2, 3]
arr.push(500); // [ 1, 2, 3, 500]

You can also use an array index to read a certain element or modify it:

const arr = [ 1, 2 ];

arr[0] = 123;

console.log(arr); // [ 123, 2]

But what if the length of an array equals 4, and we try to “modify” the sixth element?

JavaScript in this case is very liberal and allows us to shoot our own foot. The new element will be added into the array and the length will change.

But there’s a surprise! Take a look:

Same code with additional logging:

const arr = [ 1, 2, 3, 4 ];
arr[5] = 'Hello, world!';

console.log(arr); // [ 1, 2, 3, 4, <1 empty item>, 'Hello, world!' ]
console.log(arr.length); // 6

ANSWER: The length of the array will change, and the number 6 will be displayed on the screen.