JAVASCRIPT • COLLECTIONS AND STRINGS

Array Creation & Access — Create arrays and access/update elements

Learn how JavaScript arrays let you store, retrieve, and update collections of data using numeric indices.

Historical Context & Motivation

Before programming languages had arrays, early programmers had to create a separate variable for every single piece of data they wanted to track. Imagine you needed to store the scores of 100 students — that meant writing out 100 individual variable names like score1, score2, and so on. This approach was tedious, error-prone, and nearly impossible to scale. The need for a single structure that could hold multiple values under one name became one of the most important problems in early computer science.

1957
Fortran Introduces Arrays
IBM's Fortran language was among the first to support arrays, allowing scientists to group numerical data into indexed collections for mathematical computations.
1972
C Language Refines Array Access
The C programming language introduced zero-based indexing for arrays, a convention that would influence nearly every language that followed, including JavaScript.
1995
JavaScript Is Born
Brendan Eich created JavaScript in just 10 days at Netscape. Arrays were included from the start as dynamic, flexible data structures that could hold mixed data types.
2015
ES6 Modernizes Arrays
ECMAScript 2015 (ES6) added powerful new array features such as destructuring, the spread operator, and methods like Array.from(), making arrays even more versatile.

The central question that arrays solve is straightforward: how do you store and organize a list of related values so you can efficiently access any one of them? In JavaScript, arrays answer this question with elegance and flexibility, letting you group data together and retrieve individual items by their position number. Understanding how to create arrays and access their elements is the foundation for working with any collection of data.

Core Principles & Definitions

A JavaScript array is an ordered collection of values stored under a single variable name. Each value in the array is called an element, and every element has a numeric position called its index. Before diving into syntax, let's establish the foundational ideas that make arrays work.

1

Zero-Based Indexing

Array indices start at 0, not 1. The first element is at index 0, the second at index 1, and so on. This is a convention inherited from the C language.
2

Dynamic Length

Unlike arrays in some other languages, JavaScript arrays can grow and shrink at any time. You don't need to declare a fixed size when you create one.
3

Mixed Data Types

A single JavaScript array can hold numbers, strings, booleans, objects, and even other arrays. There is no restriction that all elements must be the same type.
4

Bracket Notation

You access and update elements using square brackets: myArray[index]. This syntax is used for both reading and writing values.
5

The length Property

Every array has a built-in .length property that tells you how many elements it contains. The last valid index is always length − 1.
✦ KEY TAKEAWAY
Think of an array like a row of numbered lockers in a school hallway. Each locker (element) has a number on it (its index), starting from locker 0. You can walk up to any locker and open it to see what's inside (access), swap its contents for something new (update), or even add more lockers at the end of the row (push). The hallway sign showing the total number of lockers is the .length property.

Visual Explanation — Array Structure

The diagram below shows how a JavaScript array is structured in memory. Each box represents one element, and the number above it is its index. Notice how the indices start at 0 and increment by 1 for each successive element.

The five elements of the fruits array sit at indices 0 through 4. The lower section shows the four fundamental operations: accessing a value with bracket notation, updating an element by assigning to its index, reading the .length property, and using length − 1 to reach the last element.

The key detail to remember is that index numbers always start at 0. This means the fifth element lives at index 4, not index 5. Many beginners make "off-by-one" errors by forgetting this rule, so it's worth practicing until it becomes second nature.

How Array Creation & Access Works

Two Ways to Create Arrays

JavaScript gives you two primary ways to create an array. The most common and recommended approach is the array literal syntax, which uses square brackets. The second approach uses the Array constructor, though this is less common in practice.

ARRAY LITERAL SYNTAX
let colors = ["red", "green", "blue"];
Square brackets enclose a comma-separated list of values. This creates an array with 3 elements at indices 0, 1, and 2.
ARRAY CONSTRUCTOR SYNTAX
let colors = new Array("red", "green", "blue");
The new Array() constructor produces the same result, but the literal syntax is preferred because it is shorter and less error-prone.

Accessing Elements

To read a specific element, you use the array name followed by the index in square brackets. The general pattern is arrayName[index]. If you try to access an index that doesn't exist in the array, JavaScript returns undefined rather than throwing an error. This is important to watch for because it can cause silent bugs in your programs.

INDEX FORMULA
lastIndex = array.length − 1
Because indexing starts at 0, an array with n elements has valid indices from 0 to n − 1. Accessing array[array.length] will always return undefined.

Updating Elements

To change a value at a specific position, assign a new value to that index using the assignment operator. For example, colors[0] = "purple" replaces "red" with "purple" at index 0. The array's length does not change when you update an existing element. However, if you assign a value to an index beyond the current length, JavaScript will expand the array and fill the gap with undefined slots — something you generally want to avoid.

Detailed Breakdown — Ways to Create & Populate Arrays

While the array literal is the most straightforward method, JavaScript provides several other approaches for creating arrays in different scenarios. The following diagram and table summarize the most useful techniques you'll encounter.

Six common ways to create arrays in JavaScript. Methods ①, ②, and ⑤ are the ones you'll use most frequently. Method ④ can cause confusion because new Array(3) creates three empty slots rather than an array containing the number 3.
Comparison of array creation techniques
MethodSyntaxBest Use Case
Array Literal[1, 2, 3]When you know the values upfront
Empty + push[] → .push()Building an array from user input or a loop
Array.from()Array.from(source)Converting a string or iterable to an array
Spread copy[...original]Duplicating an array without affecting the original
fill()new Array(n).fill(v)Creating an array of identical default values

Worked Example — Building a Student Gradebook

Let's walk through a realistic scenario: you're creating a small gradebook program. You need to store five quiz scores, read specific scores, update one that was entered incorrectly, and find the last score in the array.

Gradebook Array Operations
1
Step 1 — Create the ArrayStart by storing five quiz scores using an array literal. We assign the array to a variable called scores.
let scores = [88, 92, 75, 100, 84];
2
Step 2 — Access the First ScoreTo see the first quiz score, we use index 0. Remember, the first element is always at position 0, not position 1.
scores[0] // → 88
3
Step 3 — Access the Third ScoreThe "third" score in everyday language is at index 2 (since we start counting from 0). Index 0 is first, index 1 is second, index 2 is third.
scores[2] // → 75
4
Step 4 — Update an Incorrect ScoreOops — the score of 75 at index 2 should have been 79. We fix it by assigning a new value to that index using the equals sign. The old value is replaced immediately.
scores[2] = 79; // scores is now [88, 92, 79, 100, 84]
5
Step 5 — Find the Last Score Using lengthInstead of hard-coding index 4, we use scores.length - 1 to dynamically find the last index. This technique works no matter how many scores are in the array, making your code more flexible and less likely to break.
scores[scores.length - 1] // → 84
6
Step 6 — Check the Array LengthThe .length property confirms how many elements exist. After updating index 2, we still have 5 elements — updating a value doesn't change the array size.
scores.length // → 5
⚠️ Common Pitfall
If you accidentally write scores[5] on this 5-element array, you won't get an error — you'll get undefined. This is a frequent source of bugs. Always double-check that your index is within the range 0 to length − 1.

Arrays vs. Other Data Structures

Arrays are not the only way to store collections of data in JavaScript. Understanding when to use an array versus another structure will help you pick the right tool for each situation. The table below compares arrays with two other common options: objects and plain variables.

When to choose arrays over other data structures
FeatureArrayObjectSeparate Variables
Access methodNumeric index: arr[0]Named key: obj.nameVariable name: score1
Order guaranteed?Yes — elements maintain insertion orderMostly yes (with caveats)N/A — no grouping
Easy to loop through?Very easy with for loopsPossible but less intuitiveNo — must reference each one
Best forLists of similar items (scores, names, prices)Entities with named properties (a student, a car)A small number of unrelated values
ScalabilityExcellent — handles thousands of elementsGood for structured dataPoor — unmanageable beyond a handful
✦ KEY TAKEAWAY
Use an array when you have a list of similar items where position matters and you might need to loop through them. Use an object when each piece of data has a meaningful name (like firstName or age). Think of arrays as ordered lists and objects as labeled filing cabinets.

Connection to Advanced Array Concepts

Once you master creation and basic access, JavaScript arrays open up a world of powerful built-in methods. The skills you've learned in this lesson — understanding indices, using bracket notation, and working with .length — form the foundation for everything that comes next.

Today's foundations and the advanced topics they unlock
What You Learned TodayWhat Comes Next
Creating arrays with []Destructuring: let [a, b] = arr;
Accessing with arr[i]Looping with for...of, .forEach(), and .map()
Updating with arr[i] = valSplicing: .splice() for inserting/removing at any position
Using .lengthSearching: .indexOf(), .find(), .includes()
Adding with .push()Sorting: .sort() and .reverse()

As you move forward, you'll also encounter multidimensional arrays (arrays inside arrays), which are used to represent grids, game boards, and tables of data. For example, let grid = [[1,2],[3,4]]; creates a 2×2 grid where grid[0][1] accesses the value 2. Every one of these advanced patterns relies on the bracket-notation access you practiced today.

Practice Problems

PROBLEM 1 — CONCEPTUAL
An array called pets contains 7 elements. What is the index of the first element and the index of the last element? Why aren't they 1 and 7?
PROBLEM 2 — BASIC CALCULATION
Given let temps = [72, 68, 74, 80, 65];, write the code to: (a) access the value 74, (b) change 65 to 70, and (c) find the array's length.
PROBLEM 3 — INTERMEDIATE
You have let colors = ["red", "green", "blue"];. Without hard-coding any index numbers, write code that (a) accesses the last element and (b) replaces the last element with "yellow". Your code should still work if the array had 100 elements.
PROBLEM 4 — APPLIED
You're building a to-do list app. Start with an empty array called tasks. Add three tasks using .push(): "Buy groceries", "Do homework", and "Walk dog". Then the user realizes "Do homework" was already done, so update it to "Practice guitar". Write all the code and show what the final array looks like.
PROBLEM 5 — CRITICAL THINKING
Consider this code: let data = [10, 20, 30]; data[5] = 60; console.log(data.length); console.log(data[3]); What does data.length print and why? What does data[3] print? Explain why this behavior could cause bugs in a real program and how you would avoid it.

Lesson Summary

JavaScript arrays are ordered collections of values created using array literal syntax with square brackets: let arr = [val1, val2, val3];. Each value is an element stored at a numeric index that starts at 0. You access elements with bracket notation (arr[i]) and update them by assigning a new value to that index (arr[i] = newVal).

The .length property reports the total number of elements, and the last valid index is always length − 1. JavaScript arrays are dynamic (they can grow and shrink) and can hold mixed data types. Accessing an out-of-bounds index returns undefined rather than an error. Use .push() to add elements to the end, and always prefer sequential access patterns to avoid creating sparse arrays with empty holes.

Varsity Tutors • JavaScript • Array Creation & Access