Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"push()" method returns the length of array instead of array (JavaScript) [duplicate]

I want to make a new array by adding an element to an existing array by "push()" method.

This is the existing array:

let arr = [{label: 1, value: 1}, {label: 2, value: 2}];

This is the element I want to add to the existing array:

{label: 3, value: 3}

So this is the full code with "push()" method:

let arr = [{label: 1, value: 1}, {label: 2, value: 2}];

let newArr = arr.push({label: 3, value: 3});

console.log(newArr); // 3

But push() method returns the length of the new array which is "3" to "newArr" variable. However, what I really want is the actual new array instead of its length for "newArr" variable.

Are there any ways to get the actual new array for "newArr" variable?

like image 356
user7334203 Avatar asked May 18 '26 07:05

user7334203


1 Answers

With push you are actually mutating the original array. Immutable array extending is only available in ES2015+ (supported by all current, major browsers). You can use the spread operator ...:

const original = [1, 2];
const next = [...original, 3];
console.log(next); // [1, 2, 3]

Also new is a reserved keyword and can't be used as an identifier.