Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

Creating and Accessing Arrays

An array is an ordered collection of values. You can store any type of data: numbers, strings, objects, even other arrays. Elements are accessed by index, which starts at 0.

Creating an array

let fruits = ["apples", "pears", "plums"];

Accessing elements

console.log(fruits[0]); // "apples"
console.log(fruits[2]); // "plums"

Modifying an element

fruits[1] = "bananas";
console.log(fruits); // ["apples", "bananas", "plums"]

Live Example: Accessing an array

  document.getElementById("showFruits").addEventListener("click", function () {
    const fruits = ["apples", "pears", "plums"];
    const list = document.getElementById("fruitsList");
    list.innerHTML = "";
    fruits.forEach(function (fruit) {
      const item = document.createElement("li");
      item.textContent = fruit;
      list.appendChild(item);
    });
  });

Useful Methods for Arrays

JavaScript provides many methods to manipulate arrays. Here are the most commonly used:

push()

Adds an element to the end of the array.

let colors = ["red", "green"];
colors.push("blue");
console.log(colors); // ["red", "green", "blue"]

pop()

Removes the last element from the array.

colors.pop();
console.log(colors); // ["red", "green"]

splice()

You can add, remove, or replace elements in an array.

// Remove 1 element at index 0
colors.splice(0, 1);
console.log(colors); // ["green"]

// Add "yellow" at index 1
colors.splice(1, 0, "yellow");
console.log(colors); // ["green", "yellow"]

Live Example: push, pop, and splice

  let colors = ["red", "green", "blue"];
  const list = document.getElementById("colorsList");

  function displayColors() {
    list.innerHTML = "";
    colors.forEach(function (color) {
      const item = document.createElement("li");
      item.textContent = color;
      list.appendChild(item);
    });
  }

  document.getElementById("btnPush").addEventListener("click", function () {
    colors.push("yellow");
    displayColors();
  });

  document.getElementById("btnPop").addEventListener("click", function () {
    colors.pop();
    displayColors();
  });

  document.getElementById("btnSplice").addEventListener("click", function () {
    colors.splice(0, 1, "purple");
    displayColors();
  });

  displayColors();

Objects and Properties

An object is a collection of key: value pairs. You can store any type of data and access them using dot notation or square brackets.

Creating an object

let person = {
  name: "John",
  age: 30,
  occupation: "developer"
};

Accessing properties

console.log(person.name); // "John"
console.log(person["age"]); // 30

Live Example: Simple Object

document.getElementById("btnObject").addEventListener("click", function () {
  const person = {
    name: "John",
    age: 30,
    occupation: "developer"
  };
  document.getElementById("outputObject").innerText =
    person.name + " is " + person.age + " years old and works as a " + person.occupation + ".";
});

Methods in Objects and the this Keyword

Objects can have methods โ€” functions stored as properties. The this keyword refers to the current object.

Example

let car = {
  brand: "Dacia",
  start: function() {
    console.log("Starting " + this.brand);
  }
};

car.start(); // "Starting Dacia"

Live Example: Method with this

const car = {
  brand: "Dacia",
  start: function () {
    document.getElementById("outputCar").innerText = "Starting " + this.brand;
  }
};

document.getElementById("btnCar").addEventListener("click", function () {
  car.start();
});

Iterating over Objects and Arrays

You can loop through arrays with for, forEach, and objects with for...in.

Array

let numbers = [1, 2, 3];
numbers.forEach(function(n) {
  console.log(n);
});

Object

let book = { title: "Ion", author: "Rebreanu" };
for (let key in book) {
  console.log(key + ": " + book[key]);
}

Nested Arrays and Objects

You can have arrays inside objects and objects inside arrays. The structures can be complex.

Object with an array

let student = {
  name: "Ana",
  grades: [9, 10, 8]
};

console.log(student.grades[1]); // 10

Array with objects

let products = [
  { name: "Laptop", price: 3000 },
  { name: "Mouse", price: 100 }
];

console.log(products[0].name); // "Laptop"

Array in Object / Object in Array

These combinations are useful for complex data structures, such as user lists, shopping carts, etc.

Example: Array in an object

let team = {
  members: ["John", "Maria", "Alex"]
};

console.log(team.members[2]); // "Alex"

Example: Object in an array

let animals = [
  { species: "cat", sound: "meow" },
  { species: "dog", sound: "bark" }
];

console.log(animals[1].sound); // "bark"

๐Ÿง  Quiz โ€“ Arrays and Objects in JavaScript

Top