JavaScript Arrays

Working with Lists

Arrays are ordered collections of values. They can hold multiple items of any type.

Arrays are zero-indexed, meaning the first element is at position 0.

// Creating Arrays
const fruits = ['apple', 'banana', 'orange'];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, 'hello', true, { name: 'John' }];

// Accessing Elements
console.log(fruits[0]);     // 'apple'
console.log(fruits[1]);     // 'banana'
console.log(fruits.length); // 3

// Modifying Arrays
fruits[1] = 'grape';        // Change element
fruits.push('mango');       // Add to end
fruits.pop();               // Remove from end
fruits.unshift('kiwi');     // Add to beginning
fruits.shift();             // Remove from beginning

// Array Methods
fruits.includes('apple');   // true (check if exists)
fruits.indexOf('orange');   // 2 (find position)
fruits.slice(0, 2);         // ['apple', 'grape'] (copy portion)
fruits.splice(1, 1);        // Remove 1 element at index 1

// Looping Through Arrays
fruits.forEach(fruit => {
  console.log(fruit);
});
  • Arrays store ordered lists
  • Access by index: arr[0]
  • push() - Add to end
  • pop() - Remove from end
  • unshift() - Add to beginning
  • shift() - Remove from beginning
  • length property - Number of elements
  • Arrays are zero-indexed

Try Arrays

<div class="array-demo">
  <h3>Todo List</h3>
  <input type="text" id="todoInput" placeholder="Enter a task">
  <button onclick="addTodo()">Add Task</button>
  <button onclick="clearAll()">Clear All</button>
  <ul id="todoList"></ul>
  <p id="count">Tasks: 0</p>
</div>

Note: Arrays are perfect for storing lists of similar items. Use array methods to manipulate them efficiently.