Arrays in JavaScript are used to store multiple values in a single variable. They are ideal for holding an ordered list of items and are a subtype of the Object type.
Arrays are created using square brackets and can contain zero or more elements, which are separated by commas. It is recommended to use the const keyword when declaring arrays as it prevents the reassignment of the array identifier.
- Use the
constkeyword: Arrays should always be declared usingconstto avoid reassignment. - Array Naming: The name of the array should be plural to indicate it can hold multiple items.
- Square Brackets: Arrays are defined using opening and closing square brackets (
[]). - Initializing Elements: Place the elements inside the brackets, separated by commas.
Example:
const fruits = ["Apple", "Banana", "Cherry"];Elements in an array are accessed using their index, which starts at 0 for the first element. Each subsequent element has an index incremented by one.
Example:
let firstFruit = fruits[0]; // Accesses the first element, "Apple"
console.log(firstFruit); // Outputs: AppleThe length property of an array returns the number of elements it contains.
Example:
console.log(fruits.length); // Outputs: 3The push() method adds one or more elements to the end of an array and returns the new length.
Example:
fruits.push("Date");
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry", "Date"]The pop() method removes the last element from an array and returns that element.
Example:
let lastFruit = fruits.pop();
console.log(lastFruit); // Outputs: "Date"
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"]Arrays are powerful structures for managing ordered data in JavaScript. Understanding how to manipulate arrays using methods like push() and pop(), and properties like length, can greatly enhance your ability to handle data efficiently in your applications.
