An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
June 23, 2021 03:55 am GMT
Original Link: https://dev.to/coderslang/javascript-interview-question-49-add-a-new-array-element-by-index-2n8f
JavaScript Interview Question 49: Add a new array element by index
Will the length of the JS array change? Whats the output?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
All JavaScript arrays have the push
function. Its 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 theres 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.
Original Link: https://dev.to/coderslang/javascript-interview-question-49-add-a-new-array-element-by-index-2n8f
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To