Introduction to array
Lets learn what is array in javascript
In JavaScript, an array is a data structure used to store multiple values in a single variable. Arrays are zero-indexed, meaning the first element is at index 0, the second element at index 1, and so on. Arrays can hold values of different types, including numbers, strings, objects, and other arrays.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
let mixedArray = [1, "two", { three: 3 }, [4, 5]];
console.log(mixedArray[2]); // Output: { three: 3 }
console.log(mixedArray[3][1]); // Output: 5
How to create a array
1. Using Array Literals
let fruits = ["Apple", "Banana", "Cherry"];
2. Using the Array Constructor
let fruits = new Array("Apple", "Banana", "Cherry");
3. Using the Array.of Method
let fruits = Array.of("Apple", "Banana", "Cherry");
4. Using the Array.from Method
let str = "Hello";
let chars = Array.from(str); // ['H', 'e', 'l', 'l', 'o']
5. Creating an Empty Array
let emptyArray = [];
let emptyArray = new Array();
6. Creating an Array with a Specific Length
let arrayWithLength = new Array(3); // [undefined, undefined, undefined]
7. Using Spread Operator with an Existing Array
let existingArray = [1, 2, 3];
let newArray = [...existingArray];
8. Creating an Array with a Fixed Number of Elements
let fixedArray = Array(5).fill(0); // [0, 0, 0, 0, 0]