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 elements
  • typeof – Always returns "object" for arrays
  • Array.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 end
  • pop() - Remove the last element
  • shift() - Remove the first element
  • unshift() - Add an element to the beginning
  • length - Get the number of elements
  • indexOf() – Find index of item
  • includes() – 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 string
  • slice() – Extract portion of array
  • splice() – Add/remove at specific index
  • map() – Transform elements
  • filter() – 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);
  }
}