J. Doe
J. Doe

Reputation: 105

What is the correct way to add an element value to the end of a Javascript array?

Which one?

Upvotes: 0

Views: 2188

Answers (3)

Redu
Redu

Reputation: 26191

Depends on what you want to receive on return.

  1. If you want to receive back the added element array[array.length] = thingy // <- thingy
  2. If you want to receive back the length of the array array.push(thingy) // <- array.length
  3. If you want to receive a copy of the array with the new element added at the last position array.concat(thingy) (care for array items to be added since they get spread i.e. [].concat([1,2,3],[4,5,6]); // <- [1, 2, 3, 4, 5, 6])

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can use the second option.

arr[arr.length] = value

Array instance .length is 0-based, beginning at 0. An array having three elements [1,2,3] will have .length 3, though indexes 0 through 2 will be populated with values 1 through 3. arr[arr.length] = value sets value at index 3, where resulting .length will be 4.

Upvotes: 0

Azad
Azad

Reputation: 5272

simply use

arr.push(value);

the value will be added to the end of the array

Upvotes: 3

Related Questions