Home > Back-end >  Javascript - push String to Array returns Integer
Javascript - push String to Array returns Integer

Time:03-17

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.

CodePudding user response:

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]
console.log(arr2);

// Method 2
arr1.push(name);
console.log(arr1);

CodePudding user response:

The number 2 in this case is the length of your array.

Documentation on MDN

  • Related