JavaScript Arrays

What is an Array in JavaScript ?

An array is an sequential list of elements of same type or mutliple types.

In JavaScript, an array is basically a list that stores any number of elements. They could be integer, string etc. This is used when we want to store list of element and access them with one variable.

Example:

var numbers = [ 1 , "two" , 3 , 4, 5.5 ];
console.log(numbers)
[1, "two", 3, 4, 5.5]

Accessing an Array :

var numbers = [ 1 , "two" , 3 , 4, 5.5 ];
console.log(numbers[0]);
console.log(numbers[1]);
console.log(numbers[4]);
1
two
5.5

Modifying an Array:

var numbers = [ 1 , "two" , 3 , 4, 5.5 ];
numbers[4] = "five" ;
console.log(numbers)
1, "two", 3, 4, "five"

There are few basic function available to manipulate array-

  1. Array.push() – Adding element at the end of array.
  2. Array.pop() – Removing element from end of array.
  3. Array.shift() – Removing element from the starting of an array.
  4. Array.unshift() – Adding element at the front of an array.
  5. Array.splice() – Insertion and removal in between array.

There are many other advance function also like filter(), reduce(), forEach(), map(), some(), every() which are easy useful in array operations.

1. Array.push()

The push() method adds new items to the end of the array.

let numbers = [ 1, "two", 3, 4, 5.5 ];
numbers.push(6);
numbers.push("seven")
console.log(numbers)
1, "two", 3, 4, 5.5, 6, "seven"

2. Array.pop()

The pop() method removes the last item of an array and returns that item.

let numbers = [ 1, "two", 3, 4, 5.5 ];
numbers.pop();
console.log(numbers)
1, "two", 3, 4

3. Array.shift()

The shift() method removes the first array element.

let numbers = [ 1, "two", 3, 4, 5.5 ];
numbers.shift();
console.log(numbers);
"two", 3, 4, 5.5

4. Array.unshift()

The unshift() method adds a new element to an array at the beginning.

let numbers = [ 1, "two", 3, 4, 5.5 ];
numbers.unshift("zero");
console.log(numbers);
"zero", 1, "two", 3, 4, 5.5

5. Array.splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

splice(start, deleteCount, item1, item2)

Example:

const numbers = [1, 3, 4, 5];
numbers.splice(1, 0, 2);
// inserts at index 1
console.log(numbers);
1, 2, 3, 4, 5

Array Methods

MethodFunctionality
includes, indexOf, lastIndexOf, find, findIndex()Finding Elements
push, unshift, spliceAdding Elements
pop, shift, spliceRemoving Elements
concat, sliceCombining & Slicing Arrays
joinJoining Array Elements

JavaScript Arrays
  1. An array is an sequential list of elements of same type or mutliple types.
  2. An array is basically a list that stores any number of elements. They could be integer, string etc.