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.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

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.

SECTION 2

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.

SECTION 3

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.

let fruits = ["apple", "banana", "cherry", "date", "elderberry"];Variable name: fruits — Array length: 5 — Last index: 4index 0"apple"index 1"banana"index 2"cherry"index 3"date"index 4"elderberry"Accessing & Updating ElementsACCESS — read a valuefruits[2] → "cherry"UPDATE — change a valuefruits[1] = "blueberry"LENGTH — count elementsfruits.length → 5LAST ELEMENT — using lengthfruits[fruits.length - 1]
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.

SECTION 4

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

letcolors=["red","green","blue"];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

letcolors=newArray("red","green","blue");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−1lastIndex = 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.

SECTION 5

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.

Array Creation Methods at a Glance① Array Literal (most common)let a = [10, 20, 30];Creates [10, 20, 30] — length: 3② Empty Array + Pushlet a = [];a.push(10); a.push(20);③ Array.from()let a = Array.from("hello");Creates ["h","e","l","l","o"]④ Array Constructorlet a = new Array(3);Creates 3 empty slots — use with care!⑤ Spread Operator (copy)let b = [...a];Creates a shallow copy of array a⑥ Array.fill()let a = new Array(5).fill(0);Creates [0, 0, 0, 0, 0]💡 Tip: Use array literals [] for most cases — they are the clearest and safest option.Use .push() when building arrays dynamically, and [...arr] when you need a copy.
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.
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

Comparison of array creation techniques

SECTION 6

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. 1

    Step 1 — Create the Array

    Start 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. 2

    Step 2 — Access the First Score

    To 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. 3

    Step 3 — Access the Third Score

    The "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. 4

    Step 4 — Update an Incorrect Score

    Oops — 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. 5

    Step 5 — Find the Last Score Using length

    Instead 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. 6

    Step 6 — Check the Array Length

    The .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.

SECTION 7

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.

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

When to choose arrays over other data structures

✦

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.

SECTION 8

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.

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()

Today's foundations and the advanced topics they unlock

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.

SECTION 9

Practice Problems

Question 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?
Show answer
The first element is at index 0 and the last element is at index 6. JavaScript uses zero-based indexing, which means counting starts at 0 instead of 1. Because the first slot is 0, the seventh slot is 0 + 6 = 6. In general, the last valid index is always array.length − 1. Trying to access pets[7] would return undefined because that index doesn't exist.

Question 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.
Show answer
(a) The value 74 is the third element, so it lives at index 2: temps[2] returns 74. (b) The value 65 is at index 4 (the fifth and last element), so we write temps[4] = 70;. The array becomes [72, 68, 74, 80, 70]. (c) temps.length returns 5 because there are still five elements — updating a value doesn't add or remove elements.

Question 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.
Show answer
(a) To access the last element dynamically, use colors[colors.length - 1]. Since colors.length is 3, this evaluates to colors[2], which is "blue". (b) To replace it: colors[colors.length - 1] = "yellow";. This pattern is crucial because it adapts to any array length. If the array later grows to 100 elements, colors.length - 1 would be 99, correctly pointing to the last item.

Question 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.
Show answer
First, create the empty array: let tasks = [];. Then push three items: tasks.push("Buy groceries"); tasks.push("Do homework"); tasks.push("Walk dog");. After these pushes, tasks is ["Buy groceries", "Do homework", "Walk dog"]. "Do homework" is at index 1, so we update it: tasks[1] = "Practice guitar";. The final array is ["Buy groceries", "Practice guitar", "Walk dog"] with a length of 3.

Question 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.
Show answer
data.length prints 6 because JavaScript automatically extends the array to accommodate index 5, making the array six slots long. data[3] prints undefined because indices 3 and 4 were never assigned values — they are "empty slots" (sometimes called "holes"). This behavior is dangerous because .length reports 6 even though only 4 values were actually set, which can lead to incorrect calculations if you loop through the array expecting real data at every position. To avoid this, use .push() to add elements sequentially rather than assigning to arbitrary indices.

SUMMARY

Lesson Summary

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