You are on page 1of 3

Array.

indexOf()
Use indexOf() to find the position of an element:
var array = ['one', 'two', 'three'];
array.indexOf('two'); // 1
array.indexOf('four'); // -1

Array.push()
Use push() to append an element to the end of an array:
var array = [];
array.push('foo');
array; // [ 'foo' ]

Or append multiple elements:

var array = ['foo'];


array.push('bar', 'baz');
array; // [ 'foo', 'bar', 'baz' ]

What does the method return?

var array = ['foo'];


var result = array.push('bar');
result; // 2
result === array.length; // true

Array.pop()
Use pop() to remove the last element from an array:
var array = ['first', 'last'];
array.pop();
array; // [ 'first' ]

What does the method return?

var array = ['first', 'last'];


var result = array.pop();
result; // 'last'

Array.unshift()
Use unshift() to insert an element to the beginning of an array:
var array = ['foo'];
array.unshift('first');
array; // [ 'first', 'foo' ]

What does the method return?


var array = ['foo'];
var result = array.unshift('first');
result; // 2
result === array.length; // true

Array.shift()
Use shift() to remove the first element from an array:
var array = ['first', 'last'];
array.shift();
array; // [ 'last' ]

What does the method return?

var array = ['first', 'last'];


var result = array.shift();
result; // 'first'

Array.slice()
Use slice() to extract element(s) from an array:
var array = ['one', 'two', 'three'];
var start, end;

// extract elements from index 1 to end


start = 1;
array.slice(start); // [ 'two', 'three' ]

// extract 1 element from the end


start = -1;
array.slice(start); // [ 'three' ]

// extract elements from index 1 to 2


start = 1;
end = 2;
array.slice(start, end); // [ 'two' ]

What does the method return?

var array = ['one', 'two', 'three'];


var result = array.slice();
result; // [ 'one', 'two', 'three' ]

Because the method returns a shallow copy of the array, this means
that objects are passed by reference.

Array.splice()
Use splice() to mutate an array:
var array = ['one', 'two', 'three'];
// remove elements from index 1 to end
array.splice(1); // [ 'two', 'three' ]
array; // [ 'one' ]

You can remove a set number of elements:

var array = ['one', 'two', 'three'];


var start, number;

// remove 1 element from index 0


start = 0;
number = 1;
array.splice(start, number); // [ 'one' ]
array; // [ 'two', 'three' ]

You might also like