Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading