what is Array?
An array is an object which can store multiple values. Arrays store data as elements & we can use when we want, which can hold more than one value.
const animals = ["Lion", "Tiger", "Cheetah"]
It is an Array which stores 3 values
How array is declared
There are two ways to create a empty arrays :
➜ let arr = new Array();
➜ let arr = [];
The most used and easy to create an empty array is second one using brackets. In the brackets we can add multiple values and array elements which always start from '0' as index. and each value is embeded in double quotation " " and separated by comma.
const animals = ["Lion", "Tiger", "Cheetah"]
console.log(animals[0]); // Lion
console.log(animals[1]); // Tiger
console.log(animals[2]); // Cheetah
We know that array can store more than one value, If we want to add more than one value to the existing array Just assign the new value to the next index.
animals[3] = "deer";
console.log(animals[3]); // deer
If you want to replace any index with other value, assign the respective index to the value.
Output in console
You can see Changed the index[1] value to "elephant" from "tiger".
Array Basic methods
- Push
- Pop
- Shift
- Unshift
➜ First we have to understand queue & Stack how the elements enter and exit through it.
➜ In stacks, The last pushed element received first, that’s also called LIFO (Last-In-First-Out) principle.
➜ LIFO : the last element which entered into the stack will be removed first. ➜ FIFO: the first element which entered into the queue will be removed first.
➜ Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements, both to/from the beginning or the end.
Push: adds an element to the end. Pop : takes an element from the end.
Methods that work with array
push: It addes the element into the array
const animals = ["Lion" , "Tiger", "Cheetah"]
animals.push("gorilla");
console.log(animals); // Lion, Tiger, Cheetah, gorilla
The new element added into the array called "gorilla"
Pop: Removes the element from the end.
const animals = ["Lion" , "Tiger", "Cheetah"]
animals.pop();
console.log(animals); // Lion , Tiger
Poped the last element from the array (Cheetah got removed)
shift : It removes the element from the front/beginning of the array.
const animals = ["Lion" , "Tiger", "Cheetah"]
animals.shift();
console.log(animals); // Tiger, Cheetah
unshift : It adds the element through beginning of the array
const animals = ["Lion" , "Tiger", "Cheetah"]
animals.unshift("kingkong");
console.log(animals);
Here, kingkong is added to the array from the front.
That's all for Now!!