5
Hello. Whenever I need to add a new index in an array I use the second method, but I see some using the first one and I don’t know if there is any difference between them.
5
Hello. Whenever I need to add a new index in an array I use the second method, but I see some using the first one and I don’t know if there is any difference between them.
5
The method push
adds a value to the array and returns the new number of items.
var navegadores = ["Google Chrome", "Firefox"];
navegadores.push("Opera");
// retorno: 3
The second way you usually use takes the full size of the array navegadores.length
and assigns a value in that position.
var navegadores = ["Google Chrome", "Firefox"];
navegadores[navegadores.length] = "Opera";
// retorno: Opera
It is recommended to push because it is already a native method for this function, and the syntax is clearer for those reading your code.
Recommended reading: MDN - Array.prototype.push()
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.