Arrays and Methods

Beginner
80 XP
30 min
Lesson Content

Arrays and Methods

Arrays are ordered collections of values. They're one of the most important data structures in JavaScript.

Creating Arrays

let fruits = ['apple', 'banana', 'orange'];
let numbers = [1, 2, 3, 4, 5];
let mixed = ['text', 42, true];

Common Array Methods

  • push() - Add to end: fruits.push('grape')
  • pop() - Remove from end: fruits.pop()
  • shift() - Remove from start: fruits.shift()
  • unshift() - Add to start: fruits.unshift('kiwi')
  • length - Get array size: fruits.length
  • indexOf() - Find index: fruits.indexOf('banana')
  • map() - Transform each element: nums.map(n => n * 2)
  • filter() - Filter elements: nums.filter(n => n > 2)
  • forEach() - Loop through: fruits.forEach(f => console.log(f))
Example Code

Work with arrays using various methods

const nums = [1, 2, 3, 4, 5];

// Double each number
const doubled = nums.map(n => n * 2);
console.log('Doubled:', doubled);

// Filter even numbers
const evens = nums.filter(n => n % 2 === 0);
console.log('Evens:', evens);

// Sum all numbers
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log('Sum:', sum);

// Add new number
nums.push(6);
console.log('After push:', nums);

Expected Output:

Doubled: [2,4,6,8,10]
Evens: [2,4]
Sum: 15
After push: [1,2,3,4,5,6]
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code