JavaScript Arrays - Exercise 1

An array in JavaScript is an ordered list of values. The most common way to create one is with array literal syntax - just wrap your values in square brackets, separated by commas. You can also use the Array constructor, though the literal approach is almost always preferred because it's shorter and clearer.

javascript

// Array literal - the go-to approach
const fruits = ['apple', 'banana', 'cherry'];

// Mixed types are perfectly fine
const mixed = [1, 'hello', true, null];

// Empty array
const empty = [];

// Using the Array constructor (less common)
const nums = new Array(1, 2, 3);

console.log(fruits); // ['apple', 'banana', 'cherry']
console.log(mixed.length); // 4

Arrays in JavaScript use zero-based indexing, which means the first element lives at index 0, the second at 1, and so on. You access elements using bracket notation with the index number. Try to access an index that doesn't exist and you'll get undefined - JavaScript won't throw an error.

javascript

const colors = ['red', 'green', 'blue'];

console.log(colors[0]); // 'red'   - first element
console.log(colors[1]); // 'green' - second element
console.log(colors[2]); // 'blue'  - third element
console.log(colors[5]); // undefined - index doesn't exist

// Access the last element without knowing the length
console.log(colors[colors.length - 1]); // 'blue'

Every array has a built-in length property that tells you how many elements it contains. It's not a method - you don't call it with parentheses, you just read it like a property. Worth knowing: length always reflects the highest index plus one, so sparse arrays (with gaps) can have a length larger than the number of actual values.

javascript

const animals = ['cat', 'dog', 'bird', 'fish'];

console.log(animals.length); // 4

const empty = [];
console.log(empty.length); // 0

// length is also writable - you can use it to truncate
animals.length = 2;
console.log(animals); // ['cat', 'dog']

Use push() to add one or more elements to the end of an array. It modifies the original array in place and returns the new length of the array - handy if you need to know how big the array is after the addition. You can push multiple values at once by passing them as separate arguments.

javascript

const stack = ['a', 'b', 'c'];

stack.push('d');
console.log(stack); // ['a', 'b', 'c', 'd']

// push returns the new length
const newLength = stack.push('e', 'f');
console.log(newLength); // 6
console.log(stack);     // ['a', 'b', 'c', 'd', 'e', 'f']

pop() removes and returns the last element from an array. Unlike push(), it only ever removes one item at a time. If you call pop() on an empty array, it simply returns undefined without throwing an error. Together, push and pop let you use an array as a stack (last in, first out).

javascript

const stack = ['x', 'y', 'z'];

const removed = stack.pop();
console.log(removed); // 'z'
console.log(stack);   // ['x', 'y']

// pop on an empty array
const empty = [];
console.log(empty.pop()); // undefined

unshift() inserts one or more elements at the beginning of an array and shifts existing elements to higher indexes. It returns the new length of the array. Keep in mind that unshift() is generally slower than push() for large arrays because every existing element has to be re-indexed.

javascript

const queue = ['b', 'c', 'd'];

queue.unshift('a');
console.log(queue); // ['a', 'b', 'c', 'd']

// Add multiple elements at once
queue.unshift('x', 'y');
console.log(queue); // ['x', 'y', 'a', 'b', 'c', 'd']

shift() removes and returns the first element of an array, shifting all remaining elements down by one index. Paired with push(), it gives you queue behaviour (first in, first out). Like pop(), calling it on an empty array returns undefined rather than throwing.

javascript

const queue = ['first', 'second', 'third'];

const served = queue.shift();
console.log(served); // 'first'
console.log(queue);  // ['second', 'third']

// Useful for processing items in order
while (queue.length > 0) {
    console.log('Processing:', queue.shift());
}
// Processing: second
// Processing: third

indexOf() searches the array from left to right and returns the index of the first match. If the element isn't found, it returns -1. It uses strict equality (===) for comparisons, so it won't match loosely. There's also lastIndexOf() if you need to find the last occurrence instead of the first.

javascript

const letters = ['a', 'b', 'c', 'b', 'd'];

console.log(letters.indexOf('b'));    // 1 - first occurrence
console.log(letters.lastIndexOf('b')); // 3 - last occurrence
console.log(letters.indexOf('z'));    // -1 - not found

// Common pattern: check existence
if (letters.indexOf('c') !== -1) {
    console.log('c is in the array');
}

Use Array.isArray() - it's the reliable, purpose-built way to check. Avoid using typeof for this; typeof [] returns 'object', which is true for all objects and isn't helpful. instanceof Array can also work but breaks across different JavaScript execution contexts (like iframes), so Array.isArray() is the safer choice.

javascript

console.log(Array.isArray([1, 2, 3]));   // true
console.log(Array.isArray('hello'));      // false
console.log(Array.isArray({ a: 1 }));    // false
console.log(Array.isArray(undefined));   // false

// Why typeof falls short
console.log(typeof []);        // 'object' - not useful
console.log(typeof {});        // 'object' - same result!
console.log(Array.isArray([])); // true    - clear and correct

forEach() calls a provided function once for each element in the array, in order. The callback receives the current element, its index, and a reference to the array itself. It's great when you just want to do something with each item and don't need a transformed result. One thing to know: forEach always returns undefined - you can't chain it or collect results from it the way you can with map.

javascript

const scores = [85, 92, 78, 95];

// Basic usage
scores.forEach((score) => {
    console.log(score);
});
// 85, 92, 78, 95

// With index
scores.forEach((score, index) => {
    console.log(`Score ${index + 1}: ${score}`);
});
// Score 1: 85
// Score 2: 92
// Score 3: 78
// Score 4: 95