Akhil Raj
Akhil Raj

Reputation: 477

what does a.push() adds value to in an array?

My question is if in javascript, I make an array a = [2, 3, 4, 5] and type a[5] = 10 and then a.push(5) then does the compiler adds 5 to end of an array or to the first undefined spot?

I found out that it adds to the end of array , that is a[6] == 5 . but then my question is how does compiler finds if an array has ended ? of course it cannot decide that an array has ended if it identifies an unidentified value because then array would have ended after value 5 . So,how does it know that array has ended?

Upvotes: 1

Views: 85

Answers (2)

Amit
Amit

Reputation: 46323

The push operation pushes values starting at a[a.length], which results in the array growing by N items (1 in the described example).

The length is determined by the largest used index, so in your example [5] if the largest index and 6 is the length.

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128791

The summary from MDN for Array.prototype.push():

The push() method adds one or more elements to the end of an array and returns the new length of the array.

It knows where the end is because the length of the array is always numerically greater than the highest index in the array.

var a = [1, 2, 3];

a[49] = 4;

document.write(a.join(" - "));
document.write("<br>");
document.write("Array length: " + a.length);
document.write("<br>");

a.push(5);

document.write("<br>");
document.write(a.join(" - "));
document.write("<br>");
document.write("Array length: " + a.length);

Upvotes: 6

Related Questions