array

Arrays in JavaScript are ordered collections of values that can hold different data types, such as numbers, strings, or objects. They are denoted by square brackets [] and allow you to store and manipulate multiple items in a single variable. Arrays are zero-indexed, meaning the first element is accessed using index 0, the second with index 1, and so on. They offer various built-in methods for adding, removing, and manipulating elements, making them fundamental for managing and organizing data in JavaScript.

simple array


let fruits = ["apple", "orange", "banana"];
console.log(fruits); // (3) 0: "apple" 1: "orange" 2: "banana" length: 3
console.log(fruits[1]); // orange 
      

replace certain element in array using index number


let fruits = ["apple", "orange", "banana"];
fruits[0] = "coconut";
console.log(fruits); // (3) 0:"coconut" 1:"orange" 2:"banana" length 3

      

add element to the end of array


let fruits = ["apple", "orange", "banana"];
fruits.push("lemon"); // add an element
console.log(fruits); // (4) 0: "apple" 1: "orange" 2: "banana" 3: "lemon"

      

remove last element


let fruits = ["apple", "orange", "banana"];
fruits.pop(); // remove last element
console.log(fruits); // (2) 0: "apple" 1: "orange"

      

add element to beginning


let fruits = ["apple", "orange", "banana"];
fruits.unshift("mango"); // add element to beginning
console.log(fruits); // (4) 0: "mango" 1: "apple" 2: "orange" 3: "banana"
      

remove element from beginning


let fruits = ["apple", "orange", "banana"];
fruits.shift(); // remove element from beginning
console.log(fruits); // (2) 0: "orange" 1: "banana"
      

array length


let fruits = ["apple", "orange", "banana", "mango", "lemon"];
let length = fruits.length;
console.log(length); // 5
      

array index


let fruits = ["apple", "orange", "banana", "mango", "lemon"];
let index = fruits.indexOf("banana");
console.log(index); // 2