Javascript Arrays

Overview

Arrays are lists of items, such as numbers or strings, or any Javascript data type.

Declaring Arrays


An array is declared using square brackets, [], including the items of the array between the brackets.


	let data = [1,2,3,4,5];
	

Empty lists can be declared as follows:


	let data = [];
	

Accessing Array Elements


Any element of the array can be accessed by listing the array variable name, followed by square brackets enclosing the index of the element you want. Note that arrays are zero index based, meaning the first item in the array has an index of 0.


	let data = [1,2,3,4,5];
	
	let item0 = data[0];
	//item0 is 1
	
	let item2 = data[2];
	//item2 is 3
	
Try it!

Adding Items


Items can be added to an array through one of three methods.

  • push - adds an element to the end of the list
  • unshift - adds an element to the front of the list
  • splice - adds items to a specified index


	let data = [];
	data.push(1);
	data.push(2);
	
	let size = data.length;
	

Removing Items

Items can be removed from a list using one of several different methods:

  • pop - removes the last item of the list
  • shift - removes the item at the front of the list
  • splice - removes the item at the inputted index.



	let data = [1,2,3,4,5];
	data.shift();
	data.pop();