Arrays in JavaScript
Arrays in JavaScript are used to store multiple values in a single variable. They are
one of the most commonly used data structures.
1. Creating Arrays
Using Array Literals
The simplest way to create an array.
const fruits = ["Apple", "Banana", "Cherry"];
Using the Array Constructor
An alternative method to create an array.
const numbers = new Array(10, 20, 30);
const emptyArray = new Array(5); // Creates an array with 5 empty slots
2. Accessing Elements
Array elements are accessed using their index, starting at 0.
console.log(fruits[0]); // Output: Apple
fruits[1] = "Blueberry"; // Modify the second element
console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry"]
3. Array Methods
Adding and Removing Elements
push: Adds an element to the end of the array.
fruits.push("Date");
console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry", "Date"]
Arrays in JavaScript are used to store multiple values in a single variable. They are
one of the most commonly used data structures.
1. Creating Arrays
Using Array Literals
The simplest way to create an array.
const fruits = ["Apple", "Banana", "Cherry"];
Using the Array Constructor
An alternative method to create an array.
const numbers = new Array(10, 20, 30);
const emptyArray = new Array(5); // Creates an array with 5 empty slots
2. Accessing Elements
Array elements are accessed using their index, starting at 0.
console.log(fruits[0]); // Output: Apple
fruits[1] = "Blueberry"; // Modify the second element
console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry"]
3. Array Methods
Adding and Removing Elements
push: Adds an element to the end of the array.
fruits.push("Date");
console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry", "Date"]