JavaScript Arrays
Learn how to use arrays to store multiple values in a single variable.
Introduction to Arrays
Arrays are used to store multiple values in a single variable. They are ordered and can hold different data types.
Creating Arrays:
You can create arrays using square brackets or the Array constructor:
let colors = ["red", "green", "blue"];
let numbers = new Array(1, 2, 3, 4);
Accessing and Modifying
Access elements using index numbers (starting at 0):
console.log(colors[0]); // "red"
colors[1] = "yellow"; // changes "green" to "yellow"
Array Properties
.length– Returns number of elementstypeof– Always returns "object" for arraysArray.isArray(arr)– Checks if a variable is an array
console.log(colors.length); // 3
console.log(Array.isArray(colors)); // true
Common Array Methods:
push()- Add an element to the endpop()- Remove the last elementshift()- Remove the first elementunshift()- Add an element to the beginninglength- Get the number of elementsindexOf()– Find index of itemincludes()– Check if item exists
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
Looping Through Arrays
Use loops to iterate through array items:
let fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// OR use for...of
for (let fruit of fruits) {
console.log(fruit);
}
Useful Methods
join()– Convert array to stringslice()– Extract portion of arraysplice()– Add/remove at specific indexmap()– Transform elementsfilter()– Filter by condition
Practice Task
Create an array of numbers and use a loop to print only even numbers:
let numbers = [1, 2, 3, 4, 5, 6];
for (let num of numbers) {
if (num % 2 === 0) {
console.log(num);
}
}