06
Arrays
Chapter 6 • Beginner
30 min
Arrays
Arrays are ordered collections of data that can hold multiple values. They are zero-indexed, meaning the first element is at index 0.
Creating Arrays
Array Literal
javascript.js
let fruits = ['apple', 'banana', 'orange'];
let numbers = [1, 2, 3, 4, 5];
let mixed = ['hello', 42, true, null];
Array Constructor
javascript.js
let emptyArray = new Array();
let sizedArray = new Array(5); // Creates array with 5 empty slots
Accessing Array Elements
javascript.js
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // 'apple'
console.log(fruits[1]); // 'banana'
console.log(fruits[2]); // 'orange'
Array Properties and Methods
Length Property
javascript.js
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // 3
Adding Elements
javascript.js
let fruits = ['apple', 'banana'];
fruits.push('orange'); // Add to end
fruits.unshift('grape'); // Add to beginning
Removing Elements
javascript.js
let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop(); // Remove from end
let firstFruit = fruits.shift(); // Remove from beginning
Finding Elements
javascript.js
let fruits = ['apple', 'banana', 'orange'];
let index = fruits.indexOf('banana'); // Returns 1
let hasApple = fruits.includes('apple'); // Returns true
Array Methods
javascript.js
let numbers = [1, 2, 3, 4, 5];
// map: Transform each element
let doubled = numbers.map(x => x * 2);
// filter: Keep only elements that meet a condition
let evens = numbers.filter(x => x % 2 === 0);
// reduce: Combine all elements into a single value
let sum = numbers.reduce((acc, x) => acc + x, 0);
Hands-on Examples
Array Basics
let fruits = ['apple', 'banana', 'orange', 'grape'];
console.log('Array:', fruits);
console.log('Length:', fruits.length);
console.log('First fruit:', fruits[0]);
console.log('Last fruit:', fruits[fruits.length - 1]);Arrays are zero-indexed collections. You can access elements using bracket notation with their index.