JavaScript Fundamentals / Arrays

Accessing Elements

✅ Accessing Array Elements

Any element in the array can be accessed using the index number. The index in the arrays starts with 0.

let a = ["HTML", "CSS", "JS"];
console.log(a[0]);   //HTML
console.log(a[1]);  //CSS

📌Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of array using the index number.

let a = ["HTML", "CSS", "JS"];
let first = a[0];
console.log("First Item: ", first);  //First Item:  HTML

♦️Accessing the Last Element of an Array

We can access the last array element using [array.length - 1] index number.

let a = ["HTML", "CSS", "JS"];
let last = a[a.length - 1];
console.log("Last Item: ", last); // Last Item: JS

⚡Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their corresponding index.

let a = ["HTML", "CSS", "JS"];
console.log(a); //[ 'HTML', 'CSS', 'JS' ]
a[1]= "Bootstrap";
console.log(a); //[ 'HTML', 'Bootstrap', 'JS' ]

✍️ Adding Elements to the Array

Elements can be added to the array using methods like push( ) and unshift( ).

  • The push( ) method add the element to the end of the array.

  • The unshift( ) method add the element to the starting of the array.

Example :

let a = ["HTML", "CSS", "JS"];
a.push("Node.js");
a.unshift("Web Development");
console.log(a); //[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]

📍Removing Elements from an Array

To remove the elements from an array we have different methods like pop( ), shift( ), or splice( ).

  • The pop( ) method removes an element from the last index of the array.

  • The shift( ) method removes the element from the first index of the array.

  • The splice( ) method removes or replaces the element from the array.

let a = ["HTML", "CSS", "JS"];
console.log("Original Array: " + a); 
// Original Array: HTML,CSS,JS

let lst = a.pop();
console.log("After Removing the last: " + a); 
// After Removing the last: HTML,CSS

let fst = a.shift();
console.log("After Removing the First: " + a); 
// After Removing the First: CSS

a.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + a); 
// After Removing 2 elements starting from index 1: CSS

➡️ Array Length

We can get the length of the array using the array length property.

let a = ["HTML", "CSS", "JS"];
let len = a.length;
console.log("Array Length: " + len);   //Array Length: 3

🖋️ Increase and Decrease the Array Length

We can increase and decrease the array length using the JavaScript length property.

let a = ["HTML", "CSS", "JS"]
a.length = 7;
console.log("After Increasing Length: ", a); 
// After Increasing Length:  [ 'HTML', 'CSS', 'JS', <4 empty items> ]

a.length = 2;
console.log("After Decreasing Length: ", a)
// After Decreasing Length:  [ 'HTML', 'CSS' ]