~/
JavaScript Arrays Basics
Quiz
...

JavaScript Arrays Basics

beginner · updated Tue Sep 08 2026Contribute

Master how to create, access, and modify arrays in JavaScript to manage data collections efficiently in your web applications.

JavaScript Arrays Basics

Arrays are ordered collections of values. They let you store multiple items in a single variable.

Creating Arrays

let empty = [];
let numbers = [1, 2, 3, 4, 5];
let fruits = ["apple", "banana", "orange"];
let mixed = [1, "hello", true, null];

Accessing Elements

Arrays use zero-based indexing:

let fruits = ["apple", "banana", "orange"];

fruits[0];  // "apple" (first element)
fruits[1];  // "banana"
fruits[2];  // "orange"
fruits[3];  // undefined (out of bounds)

Array Length

let fruits = ["apple", "banana", "orange"];
fruits.length;  // 3

// Get the last element
fruits[fruits.length - 1];  // "orange"

Adding Elements

let fruits = ["apple", "banana"];

fruits.push("orange");      // Add to end
// ["apple", "banana", "orange"]

fruits.unshift("grape");    // Add to beginning
// ["grape", "apple", "banana", "orange"]

Tip: push is faster than unshift because it doesn’t reindex.

Removing Elements

let fruits = ["apple", "banana", "orange"];

let last = fruits.pop();     // Remove from end
// last = "orange"

let first = fruits.shift();  // Remove from beginning
// first = "apple"

Modifying Elements

let fruits = ["apple", "banana", "orange"];

fruits[0] = "grape";   // Change first element
fruits[3] = "mango";   // Add to specific position

Complete Example: Todo List

let todos = [];

function addTodo(text) {
  todos.push({ text, done: false });
}

function completeTodo(index) {
  if (index >= 0 && index < todos.length) {
    todos[index].done = true;
  }
}

function listTodos() {
  todos.forEach((todo, i) => {
    let status = todo.done ? "✓" : "○";
    console.log(`${i + 1}. ${status} ${todo.text}`);
  });
}

addTodo("Learn JavaScript");
addTodo("Build a project");
listTodos();
completeTodo(0);
listTodos();

Best Practices

  1. Use descriptive names — fruits, not arr
  2. Check bounds — Don’t access out-of-range indices
  3. Use const for arrays — If you won’t reassign the variable
  4. Handle empty arrays — Check length first
  5. Use arrays for related data — Group logically

Common Mistakes

  1. Off-by-one errors — Arrays start at 0
  2. Forgetting length — Accessing undefined indices
  3. Mutating while iterating — Can skip elements
  4. Confusing push and unshift — Different performance
  5. Using for...in on arrays — Use for...of instead