JavaScript: JavaScript Array Basics

🗓 Last updated: 2026-11-30👤 Written by: Casey✓ Reviewed by: Gray🏷 Category: JavaScript Tutorial

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.

Related Array Methods:Array.isArray() unshift() forEach shift() filter push() reduce pop() map typeof for

1. What Is an Array

An array is an ordered collection of values that can hold any data type:

HTML
<!-- 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:

HTML
<!-- 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>
⚠️ Note: 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:

HTML
<!-- 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:

HTML
<!-- Script tag -->
<script>
fruits[5];   // undefined
</script>

4. length Property

length returns the number of elements in the array:

HTML
<!-- 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:

HTML
<!-- 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):

HTML
<!-- Script tag -->
<script>
fruits[5] = 'Watermelon';
// ['Apple', 'Grape', 'Orange', empty × 2, 'Watermelon']
</script>

▶ Example: Basic Array Operations

▶ Try it Yourself

6. 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
HTML
<!-- 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>
💡 Tip: Memory trick: 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 Yourself

7. Checking Arrays: Array.isArray() vs typeof

typeof returns "object" for arrays, which makes it useless for distinguishing arrays from plain objects:

HTML
<!-- Script tag -->
<script>
let arr = [1, 2, 3];
typeof arr;              // "object"  ← useless!
Array.isArray(arr);      // true      ← correct approach
</script>
⚠️ Note: 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:

HTML
<!-- 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:

HTML
<!-- Script tag -->
<script>
fruits.forEach((fruit, index) => {
  console.log(index, fruit);
});
</script>

▶ Example: forEach in Action

▶ Try it Yourself
⚠️ Note: Higher-order methods like map, filter, and reduce are even more powerful — covered in the next lesson.


Related Array Methods:Array.isArray() unshift() forEach shift() filter push() reduce pop() map typeof for

❓ FAQ

Q What is the difference between typeof and Array.isArray() for checking arrays in JavaScript?
A 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.
Q Why doesn't arr[-1] get the last element?
A Array indexes start at 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].
Q In JavaScript, should I use push or unshift to add elements to an array?
A 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

📝 Exercises

  1. Create an array of 5 city names and use forEach to display each city's number and name on the page
  2. 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
  3. Write a program that takes 5 numbers as input, stores them in an array, and displays their sum and average
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏