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.
Top comments (5)
I'd advise you consider assigning an element directly to an array index to be an anti-pattern and bad practice. As shown by your examples, this produces unexpected results and doesn't meet our requirements.
f we say add a **new array element* by index, if an array has length
n
then we should expect the result to be an array of lengthn + 1
.Both of these examples fail to meet that expectation:
Another issue is that might might overwrite an existing element:
I don't think overwriting elements or inserting empty ones is ever what we would want to do...
In my opinion, a better implementation for this interview question would be to write a function to splice a new element into array or add it to the end of the array:
Something like this would give us the expected result of an array with a newly inserted element:
For bonus points, you could allow insertion from end of array when a negative value is passed for index, and allow inserting multiple elements:
If we pass a negative position to
insertelementsAtIndex
, we insert the element before thenth
last element, and if it's out of range, we insert it at the start of the array... so-1
inserts before the last item,-2
before the second last item, etc:And if we pass an array of length
n
, andx
new elements toinsertelementsAtIndex
, we should expect an array of lengthn + x
:If this was an interview question, I suspect it would be intended to verify that you avoid assigning to element index explicitly and instead provide some implementation similar to either of these two examples.
Great comment! The original question is not about teaching beginners "how to", but rather about explaining the situation "what if".
And the best way to add a new element to the end of the JS array is by using a
push
method.Hey i was just checking your code out, it works but why splice method for me returns an empty array but works for you.
It's because
Array.splice
deletes and inserts items in array, then returns any items that were deleted. So if we don't delete any items, return value ofArray.splice(n, 0, ...items)
will always be empty[]
.In your example, you just need to log
output
as well as result ofsplice
call:And if you're wondering why you see individual characters from
elements
variable; it's because you're using rest parameter, which will spread iterable contents into function args. In case ofstring
this is the individual characters of its value.If this isn't what you want, and instead you just want to insert
string
value, you just need to remove rest operator:This is also the reason why we spread
arr
into a newoutput
array, before callingsplice
, because it mutates the array it's called on. When designing our implementation, it's better to avoid mutating input and let the consumer decide if they want to mutate.For example, consumer "mutates" by assigning output of
someFn
to previously declared variablearr
:I think the fact that
splice
is mutative leads a lot of people to avoid it. However, it's really useful! Here's some of the things you can do with it...So to summarise:
Array.splice
mutates its array.Array.splice
returns items that were deleted from its array.Array.splice
syntax is:Hope this helps explain it more ;)
Thank You for long explanantion, everything make sense now. I havent used these methods very often so forgot there nature and what it does and for some reason i havent noticed that it mutates the original array it self in mdn documentation. Stupid me...