An array in JavaScript is a special type of object that stores multiple values in a single variable. Arrays are ordered collections that allow storing multiple data types such as numbers, strings, and objects.
Arrays can be created using square brackets []
or the new Array()
constructor.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]
new Array()
(Less Common)let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]
π The first method ([]
) is more commonly used because it's simpler and more readable.
Each item in an array has an index, starting from 0
.
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // "Red"
console.log(colors[1]); // "Green"
console.log(colors[2]); // "Blue"
π If you try to access an index that doesn’t exist, it will return undefined
.
You can change an element’s value by assigning a new value to a specific index.
let cars = ["Toyota", "Honda", "Ford"];
cars[1] = "BMW";
console.log(cars); // ["Toyota", "BMW", "Ford"]
π Arrays are mutable, meaning their elements can be updated.
The .length
property returns the number of elements in an array.
let animals = ["Dog", "Cat", "Elephant"];
console.log(animals.length); // 3
π Useful when looping through an array.
push()
– Adds to the Endlet fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits); // ["Apple", "Banana", "Mango"]
pop()
– Removes from the Endfruits.pop();
console.log(fruits); // ["Apple", "Banana"]
unshift()
– Adds to the Beginningfruits.unshift("Grapes");
console.log(fruits); // ["Grapes", "Apple", "Banana"]
shift()
– Removes from the Beginningfruits.shift();
console.log(fruits); // ["Apple", "Banana"]
π These methods allow dynamic modifications of arrays.
Arrays can be iterated using loops like for
and forEach()
.
for
Looplet numbers = [10, 20, 30, 40];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
forEach()
numbers.forEach(function(num) {
console.log(num);
});
π forEach()
is more modern and readable.
includes()
– Checks if an Element is Presentlet colors = ["Red", "Green", "Blue"];
console.log(colors.includes("Green")); // true
console.log(colors.includes("Yellow")); // false
π Useful for searching within arrays.
Arrays can be combined using concat()
.
let a = [1, 2];
let b = [3, 4];
let result = a.concat(b);
console.log(result); // [1, 2, 3, 4]
π concat()
creates a new array, leaving the original unchanged.
join()
– Converts an Array into a Stringlet fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.join(", ")); // "Apple, Banana, Cherry"
π Helps when displaying array data in UI.
JavaScript arrays store multiple values, provide built-in methods for manipulation, and allow efficient iteration. Arrays are versatile and commonly used in data handling, user input storage, and looping through datasets.
@asadmukhtar