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 do not know if there is any difference between them.
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 do not know if there is any difference between them.
The push
method adds a value to the array and returns the new amount of items.
var navegadores = ["Google Chrome", "Firefox"];
navegadores.push("Opera");
// retorno: 3
The second form you use takes the total size of the array navegadores.length
and assigns a value to that position.
var navegadores = ["Google Chrome", "Firefox"];
navegadores[navegadores.length] = "Opera";
// retorno: Opera
It is recommended to use push because it is already a native method for this function, and the syntax is clearer for those who are reading your code.
Recommended reading: MDN - Array.prototype.push ()