What is the difference between element.push ("value") and element [element.length]

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 do not know if there is any difference between them.

    
asked by anonymous 23.10.2015 / 18:33

1 answer

5

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

    
23.10.2015 / 18:37