Skip to content

Javascript – push String to Array returns Integer

I add some strings in an array.

console.log(arr1); // ['product_1']
let arr2 = arr1.push(name);
console.log(arr2); // 2

Why I receive number 2 in the second log when name is a String too?

  • I tried also let arr2 = arr1.slice().push(name); without success.


arr.push() modifies the arr itself and returns the length of the resulting array, to do what you want to do, you can do one of the two following methods

const name = "test";
arr1 = ['product_1'];

// Method 1
let arr2 = [...arr1, name]

// Method 2