What is an Array in JavaScript?
In JavaScript, an array is a special variable that can hold more than one value at a time. Unlike primitive data types like numbers or strings, arrays allow us to store lists of values and access them via index positions.
How to Create an Array?
There are multiple ways to create an array:
Using Array Literals (Recommended)
let fruits = ["apple", "banana", "cherry"];
Using the Array Constructor
let numbers = new Array(1, 2, 3, 4);
While both methods work, using literals is generally simpler and more readable.
Accessing Array Elements
Array elements are accessed using zero-based indexing. The first element is at index 0.
let colors = ["red", "green", "blue"];
console.log(colors[0]); // red
console.log(colors[2]); // blue
Output:
red blue
Changing Elements in an Array
You can change the value at any index directly:
let fruits = ["apple", "banana", "cherry"];
fruits[1] = "orange";
console.log(fruits);
Output:
[ 'apple', 'orange', 'cherry' ]
How to Add or Remove Elements?
JavaScript provides several built-in methods to modify arrays:
Adding Elements
let nums = [1, 2];
nums.push(3); // Add to end
nums.unshift(0); // Add to start
console.log(nums);
Output:
[ 0, 1, 2, 3 ]
Removing Elements
nums.pop(); // Remove from end
nums.shift(); // Remove from start
console.log(nums);
Output:
[ 1, 2 ]
Array Length
The length
property gives the number of elements in the array.
let names = ["John", "Alice", "Bob"];
console.log(names.length); // 3
Looping Through Arrays
Using a for loop
let animals = ["dog", "cat", "lion"];
for (let i = 0; i < animals.length; i++) {
console.log(animals[i]);
}
Output:
dog cat lion
Using for...of
for (let animal of animals) {
console.log(animal);
}
Common Array Methods
push()
– Add to endpop()
– Remove from endshift()
– Remove from startunshift()
– Add to startindexOf()
– Find index of a valueincludes()
– Check if value existsslice()
– Extract part of arraysplice()
– Add/Remove elementsjoin()
– Convert array to string
Example: Using splice()
splice()
can remove or insert elements into an array.
let tools = ["hammer", "wrench", "screwdriver"];
tools.splice(1, 1, "pliers");
console.log(tools);
Output:
[ 'hammer', 'pliers', 'screwdriver' ]
Q&A to Build Intuition
Q: What happens if I access an index that doesn't exist?
A: You get undefined
.
let arr = ["a", "b"];
console.log(arr[10]); // undefined
Q: Can an array hold values of different types?
A: Yes. JavaScript arrays are heterogeneous.
let mixed = [1, "hello", true, null];
console.log(mixed);
Output:
[ 1, 'hello', true, null ]
Conclusion
Arrays are one of the most essential data structures in JavaScript. They allow you to store, retrieve, and manipulate collections of data with ease. Mastering array methods will drastically improve your problem-solving skills in real-world applications.