All technological notes.
Array:
Arrays are a special type of objects.
typeof array_name returns objectArray can have variables of different data types.
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
The Difference Between Arrays and Objects
The elements in an array can be different types.
let arr = [1, "2", null, { name: "John" }];
console.log(arr); //[ 1, '2', null, { name: 'John' } ]
Using const
Syntax
// Using an array literal
const array_name = [item1, item2, ...];
// create an empty array, and then provide the elements
const array_name = [];
array_name[0]= item1;
array_name[1]= item2;
array_name[2]= item3;
// Using Array object
const array_name = new Array(item1, item2, ...);
// access an item
let var_name = array_name[index];
array_name[0]; //the first item
array_name[-1]; //the last item
// Access the Full Array
let var_name = array_name;
array_name[index] = value;
push() methodconsole.log("\n-------- Array: .push() --------\n");
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
console.log(fruits); //[ 'Banana', 'Orange', 'Apple', 'Lemon' ]
length property and indexconsole.log("\n-------- Array: [length] --------\n");
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds a new element (Lemon) to fruits
console.log(fruits); //[ 'Banana', 'Orange', 'Apple', 'Lemon' ]
.length:Length of Arrayconst fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length; //4
for loopconsole.log("\n-------- Array: for loop --------\n");
const fruits = ["Banana", "Orange", "Apple", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
// 0 Banana
// 1 Orange
// 2 Apple
// 3 Mango
.forEach() functionconsole.log("\n-------- Array: .forEach() --------\n");
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.forEach((ele) => {
console.log(ele);
});
// Banana
// Orange
// Apple
// Mango