What is an Array?
Arrays are objects or special type of variables that can store multiple values at once. The multiple items are stored under a single variable name.
Creating Arrays.
There are two ways of creating arrays;
- Using array literal [ ]
For example;
const fruits= [ "banana", "apple", "orange" ];
- Using the new keyword.
For example;
const fruits= new Array( "banana", "apple", "orange");
Accessing elements of an array.
You can access elements of an array using indices (0, 1, 2 …). For example;
const fruits= [ "banana", "apple", "orange" ];
console.log(fruits); // "banana", "apple", "orange"
console.log( fruits[0] ); // "banana"
console.log( fruits[1] ); // "apple"
Note: Array indexing starts from 0, not 1
Array Methods.
Array methods make it easier to perform useful operations with arrays. Some of the commonly used JavaScript array methods are:
- push()
The push() method adds an element at the end of the array. For example,
const fruits= [ "banana", "apple", "orange" ];
fruits.push( "mango" );
console.log( fruits ); // [ "banana", "apple", "orange", "mango" ]
- pop()
The pop() method removes the last element from an array. For example;
const fruits= [ "banana", "apple", "orange" ];
fruits.pop();
console.log( fruits ); // [ "banana", "apple" ]
- unshift()
The unshift() method adds an element at the beginning of the array. For example;
const fruits= [ "banana", "apple", "orange" ];
fruits.unshift( "mango" );
console.log( fruits ); // [ 'mango', 'banana', 'apple', 'orange' ]
- shift()
The shift() method removes the first element from an array. For Example;
const fruits= [ "banana", "apple", "orange" ];
fruits.shift();
console.log( fruits ); // [ 'apple', 'orange' ]
- Array Length
We can find the length of an element (the number of elements in an array) using the length property. For example;
const fruits= [ "banana", "apple", "orange" ];
console.log( fruits.length ); // 3
- concat()
Joins two or more arrays and returns a result. For example;
const fruits = [ "banana", "apple", "orange"];
const colors = [ "red", "white", "green"];
const comb = fruits.concat( colors);
console.log(comb); // [ 'banana', 'apple', 'orange', 'red', 'white', 'green' ]
- slice()
Selects the part of an array and returns the new array. For example;
const colors = [ "red", "white", "green"];
console.log( colors.slice(1)); //[ 'white', 'green' ]
Checkout more here on JavaScript array methods.
Happy Learning!!