Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 23, 2021 03:55 am GMT

JavaScript Interview Question 49: Add a new array element by index

coderslang javascript interview question #49

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.

Learn Full-Stack JavaScript


Original Link: https://dev.to/coderslang/javascript-interview-question-49-add-a-new-array-element-by-index-2n8f

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To