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.
What Is an Array
An array is an ordered collection of values that can hold any data type:
<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.
Creating Arrays
Two ways:
<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.
Accessing Elements
Array indices start at 0, not 1. The first element is [0], the second is [1], and so on:
<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>
fruits[5]; // undefined
</script>
length Property
length returns the number of elements in the array:
<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.
Modifying Elements
Just assign a new value via the index:
<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>
fruits[5] = 'Watermelon';
// ['Apple', 'Grape', 'Orange', empty × 2, 'Watermelon']
</script>
Example: Basic Array Operations
<!DOCTYPE html>
<html>
<body>
<h2>Basic Array Operations</h2>
<div id="output"></div>
<script>
let fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Watermelon'];
let html = '<strong>Original array:</strong>' + fruits.join(', ') + '<br>';
html += '<strong>Length:</strong>' + fruits.length + '<br>';
html += '<strong>First:</strong>' + fruits[0] + '<br>';
html += '<strong>Last:</strong>' + fruits[fruits.length - 1] + '<br><br>';
fruits[1] = 'Mango';
html += '<strong>After modifying index 1:</strong>' + fruits.join(', ') + '<br>';
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
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 |
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Array Methods</title></head>
<body>
<pre id="output"></pre>
<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
<!DOCTYPE html>
<html>
<body>
<h2>Fruit List Manager</h2>
<input type="text" id="fruitInput" placeholder="Enter a fruit name">
<button onclick="addFruit()">Add to end</button>
<button onclick="removeLast()">Remove last</button>
<p id="output"></p>
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
function showFruits() {
let html = '<strong>Current fruit list:</strong><br>';
if (fruits.length === 0) {
html += '(empty list)';
} else {
for (let i = 0; i < fruits.length; i++) {
html += `[${i}] ${fruits[i]}<br>`;
}
}
html += `<br>Total: ${fruits.length} fruits`;
document.getElementById('output').innerHTML = html;
}
function addFruit() {
let name = document.getElementById('fruitInput').value.trim();
if (name) {
fruits.push(name);
document.getElementById('fruitInput').value = '';
showFruits();
}
}
function removeLast() {
if (fruits.length > 0) {
let removed = fruits.pop();
showFruits();
}
}
showFruits();
</script>
</body>
</html>
Checking Arrays: Array.isArray() vs typeof
typeof returns "object" for arrays, which makes it useless for distinguishing arrays from plain objects:
<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().
forEach for Iteration
forEach is the most common way to iterate over arrays — more declarative than a for loop:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>forEach</title></head>
<body>
<pre id="output"></pre>
<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>
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
</script>
Example: forEach in Action
<!DOCTYPE html>
<html>
<body>
<h2>forEach Array Iteration</h2>
<div id="output"></div>
<script>
let students = [
{ name: 'Alice', score: 92 },
{ name: 'Bob', score: 85 },
{ name: 'Charlie', score: 78 },
{ name: 'Diana', score: 96 }
];
let html = '<table border="1" cellpadding="8" style="border-collapse:collapse">';
html += '<tr><th>#</th><th>Name</th><th>Score</th><th>Grade</th></tr>';
students.forEach((s, i) => {
let grade = s.score >= 90 ? 'A' : s.score >= 80 ? 'B' : 'C';
let color = s.score >= 90 ? 'green' : s.score >= 80 ? 'blue' : 'orange';
html += `<tr>
<td>${i + 1}</td>
<td>${s.name}</td>
<td>${s.score}</td>
<td style="color:${color}">${grade}</td>
</tr>`;
});
html += '</table>';
let total = 0;
students.forEach(s => total += s.score);
html += `<p>Average: ${(total / students.length).toFixed(1)}</p>`;
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
map, filter, and reduce are even more powerful — covered in the next lesson.
📖 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
❓ FAQ
push and unshift return?let arr = [1].push(2) gives you 2 (the length), not [1, 2].break inside forEach?forEach has no break mechanism. To exit early, use a traditional for loop or for...of with break.arr[100] returns undefined when out of bounds — no exception is thrown. But this can hide bugs, so it's good practice to check the index range before accessing.📝 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



