Only non-negative integer indices are allowed, and unlike in Python, accessing negative indices with bracket notation does not give you access to the last elements of the array.
Subarray slicing can be done with
slice(start_index, upto_index), and the slicing indices are left-inclusive and right-exclusive.
upto_index can be ommited to extract till the end of the array, and both
upto_index can be negative to indicate an offset from the end of array.
const arr = [0, 10, 20, 30, 40, 50]; let subarray = arr.slice(2, 5); // [20, 30, 40] subarray = arr.slice(-2); // [40, 50]
Common Array Operations
push(item)adds item to the end of array and returns the array length; amortized
pop()removes and returns the last element of the array; amortized
shift()removes and returns the first element of the array;
unshift(item)adds item to the start of the array and returns the array length;
splice(start_index, count_to_remove, add_item1, add_item2, ...)removes and returns
count_to_removeitem(s) from an array given its/their index and optionally replaces them with
O(1)time append/remove at the end of an array. Some implementations also support fast prepend/remove at the beginning.
In general, to iterate through a list,
for loop is easier to reason than
for...of loops. The
for...of loop can iterate over any iterable object, such as