JavaScript Arrays
Store and manage multiple values in a single variable
📚 What are JavaScript Arrays?
Arrays are special variables that can hold more than one value at a time. Think of them as containers that can store multiple items in a single place.
// Creating an array with fruits
let fruits = ["apple", "banana", "orange"];
console.log(fruits); // ["apple", "banana", "orange"]
Output:
["apple", "banana", "orange"]
Key Array Concepts
Creating Arrays
Different ways to create arrays
let colors = ["red", "green", "blue"];
Array Index
Access items using their position
colors[0]; // "red" (first item)
Array Length
Find how many items are in array
colors.length; // 3
Adding Items
Add new items to arrays
colors.push("yellow");
🔹 Creating Arrays
There are several ways to create arrays in JavaScript:
// Method 1: Array literal (most common)
let numbers = [1, 2, 3, 4, 5];
// Method 2: Array constructor
let animals = new Array("cat", "dog", "bird");
// Method 3: Empty array
let emptyArray = [];
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(animals); // ["cat", "dog", "bird"]
console.log(emptyArray); // []
Output:
[1, 2, 3, 4, 5]
["cat", "dog", "bird"]
[]
🔹 Accessing Array Elements
Use square brackets with the index number (starting from 0):
let fruits = ["apple", "banana", "orange", "grape"];
console.log(fruits[0]); // "apple" (first item)
console.log(fruits[1]); // "banana" (second item)
console.log(fruits[3]); // "grape" (fourth item)
// Get the last item
console.log(fruits[fruits.length - 1]); // "grape"
Output:
apple
banana
grape
grape
🔹 Common Array Methods
Useful methods to work with arrays:
let colors = ["red", "green"];
// Add to end
colors.push("blue");
console.log(colors); // ["red", "green", "blue"]
// Add to beginning
colors.unshift("yellow");
console.log(colors); // ["yellow", "red", "green", "blue"]
// Remove from end
let lastColor = colors.pop();
console.log(lastColor); // "blue"
console.log(colors); // ["yellow", "red", "green"]
// Remove from beginning
let firstColor = colors.shift();
console.log(firstColor); // "yellow"
console.log(colors); // ["red", "green"]
Output:
["red", "green", "blue"]
["yellow", "red", "green", "blue"]
blue
["yellow", "red", "green"]
yellow
["red", "green"]