1

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.

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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

Documentation on MDN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.