Skip to content

Instantly share code, notes, and snippets.

@thattimc
Last active October 31, 2021 06:38
Show Gist options
  • Save thattimc/b53a2558d3f7e6fb772b864a6b419bc1 to your computer and use it in GitHub Desktop.
Save thattimc/b53a2558d3f7e6fb772b864a6b419bc1 to your computer and use it in GitHub Desktop.
Javascript array cheatsheet

Creating an Array

const array = ['one', 'two', 'three'];
or
const array = new Array('one', 'two', 'three');

Get the array index

array.indexOf('two');

Accessing Items in an Array

array[1];

Add item at the end of the array

array.push('four');

Add item at the beginning of the array

array.unshift('zero');

Remove item at the end of the array

array.pop();

Remove item at the beginning of the array

array.shift();

Removing an Item from an Array

array.splice(1, 1);

Modifying Items in Arrays

array[0] = 2;

or

array.splice(1, 1, 'four');

Looping Through an Array

for (let idx = 0; idx < array.length; idx++) {
  console.log(array[idx]);
}

or

for (let item of array) {
  console.log(item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment