JavaScript: JavaScript Array Basics
An array is like a row of numbered drawers — each drawer has a number (index) and holds something (data). You can grab items by number, swap them out, or add new ones to the end. Arrays are the data structure you'll use most in everyday development.
1. What Is an Array
An array is an ordered collection of values that can hold any data type:
<!-- Script tag -->
<script>
let arr = [1, 'hello', true, null, undefined];
</script>
A single array can mix different types, but in practice you'll usually store the same type for easier processing.
2. Creating Arrays
Two ways:
<!-- Script tag -->
<script>
// Method 1: Literal syntax (recommended — clean and direct)
let fruits = ['Apple', 'Banana', 'Orange'];
// Method 2: Array constructor
let nums = new Array(1, 2, 3);
let empty = new Array(5); // Creates an empty array of length 5, NOT [5]!
</script>
new Array(5) creates an empty array with length 5, not an array containing the number 5! This trips up many people, so just stick with the [] literal.
3. Accessing Elements
Array indices start at 0, not 1. The first element is [0], the second is [1], and so on:
<!-- Script tag -->
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
fruits[0]; // 'Apple'
fruits[1]; // 'Banana'
fruits[2]; // 'Orange'
</script>
Accessing a non-existent index won't throw an error — it returns undefined:
<!-- Script tag -->
<script>
fruits[5]; // undefined
</script>
4. length Property
length returns the number of elements in the array:
<!-- Script tag -->
<script>
let arr = [10, 20, 30];
arr.length; // 3
</script>
length is always one more than the highest index (since indices start at 0). The last element is at arr.length - 1.
5. Modifying Elements
Just assign a new value via the index:
<!-- Script tag -->
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
fruits[1] = 'Grape'; // Replace 'Banana' with 'Grape'
// ['Apple', 'Grape', 'Orange']
</script>
You can also add elements by index (not recommended — creates empty slots):
<!-- Script tag -->
<script>
fruits[5] = 'Watermelon';
// ['Apple', 'Grape', 'Orange', empty × 2, 'Watermelon']
</script>
▶ Example: Basic Array Operations
▶ Try it Yourself6. Core Methods
The most commonly used array methods for adding and removing elements:
| Method | Action | Returns |
|---|---|---|
push() |
Add to end | New length |
pop() |
Remove from end | Removed element |
unshift() |
Add to beginning | New length |
shift() |
Remove from beginning | Removed element |
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>Array Methods</title></head>
<!-- Document body -->
<body>
<pre id="output"></pre>
<!-- Script tag -->
<script>
let arr = ['a', 'b', 'c'];
arr.push('d'); // ['a','b','c','d'] returns 4
arr.pop(); // ['a','b','c'] returns 'd'
arr.unshift('z'); // ['z','a','b','c'] returns 4
arr.shift(); // ['a','b','c'] returns 'z'
document.getElementById('output').textContent = JSON.stringify(arr);
</script>
</body>
</html>
push/pop work on the tail; unshift/shift work on the head. Methods starting with p affect the end; those starting with s affect the start. un prefixed methods add; without un they remove.
▶ Example: Fruit List Manager
▶ Try it Yourself7. Checking Arrays: Array.isArray() vs typeof
typeof returns "object" for arrays, which makes it useless for distinguishing arrays from plain objects:
<!-- Script tag -->
<script>
let arr = [1, 2, 3];
typeof arr; // "object" ← useless!
Array.isArray(arr); // true ← correct approach
</script>
typeof is unreliable for arrays — always use Array.isArray().
8. forEach for Iteration
forEach is the most common way to iterate over arrays — more declarative than a for loop:
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>forEach</title></head>
<!-- Document body -->
<body>
<pre id="output"></pre>
<!-- Script tag -->
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
let result = '';
fruits.forEach(function(fruit, index) {
result += index + ' ' + fruit + '\n';
});
document.getElementById('output').textContent = result;
</script>
</body>
</html>
Arrow functions make it even more concise:
<!-- Script tag -->
<script>
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
</script>
▶ Example: forEach in Action
▶ Try it Yourselfmap, filter, and reduce are even more powerful — covered in the next lesson.
❓ FAQ
typeof and Array.isArray() for checking arrays in JavaScript?typeof [] returns "object", so it cannot distinguish an array from a plain object, while Array.isArray([]) returns true and identifies arrays accurately. You should prefer Array.isArray() for checking arrays and avoid using typeof.arr[-1] get the last element?0, so -1 is not a valid index; arr[-1] returns undefined and does not throw an error. To get the last element, use arr[arr.length - 1].push or unshift to add elements to an array?push adds elements at the end, while unshift adds them at the beginning, and both return the new length. push is more common for everyday appending, whereas unshift shifts all existing elements and has a higher performance cost.📖 Summary
- Create arrays with the
[]literal — avoidnew Array()(easy to mess up) - Indices start at 0; the last element is at index
length - 1 push/popwork on the tail;unshift/shiftwork on the head- Use
Array.isArray()to check if something is an array —typeofreturns"object"and is unreliable forEachis more declarative thanfor, but you can't usebreakto exit early
📝 Exercises
- Create an array of 5 city names and use
forEachto display each city's number and name on the page - Build a to-do list: input tasks to add to the end, click "Done" to remove the last task, and display the list in real time
- Write a program that takes 5 numbers as input, stores them in an array, and displays their sum and average