This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
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.
This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer | Sciencx (2021-06-23T03:55:04+00:00) JavaScript Interview Question #49: Add a new array element by index. Retrieved from https://www.scien.cx/2021/06/23/javascript-interview-question-49-add-a-new-array-element-by-index/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.