Adding new value to existing array in javascript
In JavaScript, you can add a new value to an existing array using several methods. Here are a few ways to do it:
-
Using the
push()
method:let arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4]
The
push()
method adds a new element to the end of the array. -
Using the
concat()
method:let arr = [1, 2, 3]; arr = arr.concat([4]); // [1, 2, 3, 4]
The
concat()
method returns a new array with the elements of the original array and the new elements. -
Using the
splice()
method:let arr = [1, 2, 3]; arr.splice(2, 0, 4); // [1, 2, 4, 3]
The
splice()
method adds a new element at a specific position (in this case, the third position) and shifts the existing elements to the right. -
Using the
unshift()
method:let arr = [1, 2, 3]; arr.unshift(4); // [4, 1, 2, 3]
The
unshift()
method adds a new element to the beginning of the array. -
Using the
spread operator (...)
:let arr = [1, 2, 3]; arr = [...arr, 4]; // [1, 2, 3, 4]
The spread operator creates a new array with the elements of the original array and the new elements.
Note that some of these methods modify the original array, while others return a new array. Be careful when using these methods to ensure you're working with the desired array.