What is an Array?
An array is an object that can store multiple values at once. For example,
const words = ['hello', 'world', 'welcome'];
Declaration of an Array
There are two ways to declare an array.
Example:
Access Elements of an Array
Array in JavaScript are indexed from '0'(zero) so we can access array elements as follows:
const myArray = ['a', 'b', 'c', 'd', 'e'];
// first element
console.log(myArray[0]); // "a"
// second element
console.log(myArray[1]); // "b"
Add an Element to an Array
You can use this method push() and unshift() to add elements to an array.
The push() method adds an element at the end of the array.
For example,
let dailyActivities = ['eat', 'sleep'];
// add an element at the end
dailyActivities.push('exercise');
console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
The unshift() method adds an element at the beginning of the array. For example,
let dailyActivities = ['eat', 'sleep'];
//add an element at the start
dailyActivities.unshift('work');
console.log(dailyActivities); // ['work', 'eat', 'sleep']
Change the Elements of an Array
You can also add elements or change the elements by accessing the index value. For Example,
let dailyActivities = [ 'eat', 'sleep'];
// this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise';
console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
Remove an Element from an Array
You can use the pop() method to remove the last element from an array. The pop() method also returns the returned value. For example,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];
// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']
// remove the last element from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();
//get removed element
console.log(removedElement); // 'sleep'
console.log(dailyActivities); // ['work', 'eat']
If you need to remove the first element, you can use the shift() method. The shift() method removes the first element and also returns the removed element. For example,
let dailyActivities = ['work', 'eat', 'sleep'];
// remove the first element
dailyActivities.shift();
console.log(dailyActivities); // ['eat', 'sleep']
Array length
You can find the length of an element (the number of elements in an array) using the length property. For example,
const dailyActivities = [ 'eat', 'sleep'];
// this gives the total number of elements in an array
console.log(dailyActivities.length); // 2