Javascript Arrays
What is Arrays in JS:
Arrays are used to store and organize multiple values in a single variable.
Creating Arrays:
Array is the data structure that you build in JavaScript using square brackets []. One of the best features of arrays is a fact that they can store different data types like numbers, strings and even arrays.
// Creating an array of numbers
let numbers = [1, 2, 3, 4, 5];
// Creating an array of strings
let fruits = ["apple", "banana", "orange"];
// Creating a mixed-type array
let mixedArray = [1, "hello", true, [2, 4, 6]];
Accessing Elements:
Array elements are accessed by specifying their index number. The array begins from position 0 -- the first element.
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: "red"
console.log(colors[2]); // Output: "blue"
Array Methods:
push()
Adds one or more elements to the end of an array.
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]
pop()
Removes the last element from the end of an array.
let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: "orange"
console.log(fruits); // Output: ["apple", "banana"]
shift()
Removes the first element from the beginning of an array.
let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits.shift();
console.log(firstFruit); // Output: "apple"
console.log(fruits); // Output: ["banana", "orange"]
unshift()
Adds one or more elements to the beginning of an array.
let fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // Output: ["apple", "banana", "orange"]
slice()
Returns a portion of an array as a new array.
let numbers = [1, 2, 3, 4, 5];
let slicedNumbers = numbers.slice(1, 4);
console.log(slicedNumbers); // Output: [2, 3, 4]
splice()
Alters the array contents by way of removing or substituting the same or by adding new items at the places of the old ones.
let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "grape", "kiwi");
console.log(fruits); // Output: ["apple", "grape", "kiwi", "orange"]