JavaScript Guide
Beginner12 minsJS Tutorial

JavaScript Arrays

Learn how to store multiple elements in a single variable, understand array indexing, properties, and core behaviors.

Lesson session

0% complete

0/5
Learn mode

Read the concept first, then inspect syntax and examples.

Study prompt

Current mode guidance

Read the concept first, then inspect syntax and examples.

Confidence

Track your comfort

55%
NewClear

Quick notes

0/240 characters

Concept switcher

Move through the idea before the code.

JavaScript arrays are global objects used to store multiple ordered values inside a single variable reference.

Example preview

Run it in your head

Creating Array & Index Access

Set up a simple array literal and retrieve items using zero-indexed positions.

const members = ["Asha", "Bishal", "Carla"];
console.log(members[0]);
console.log(members[members.length - 1]);
Output

Predict the output first, then reveal it.

Next useful links

Related pages from the same JavaScript guide.

Overview & Purpose

JavaScript arrays are global objects used to store multiple ordered values inside a single variable reference.

Topic Definition

An array is a special type of variable that can hold more than one value at a time. Elements are indexed starting from position 0. In JavaScript, arrays are dynamic and can hold elements of different data types (numbers, objects, strings, functions) simultaneously.

Why It Matters

Without arrays, you would have to declare separate variables for every item (e.g. item1, item2, item3). Arrays let you group items, iterate over them with loops, and execute array transformations like sorting, filtering, and mapping in high-performance blocks.

Syntax Guide

javascript
// Creating an array of string values
const fruitList = ["Apple", "Banana", "Cherry"];

// Accessing index zero element
let firstFruit = fruitList[0];
console.log(firstFruit);
Syntax Explanation:

Line 1: Creates an array literal containing three fruit names.

Line 4: Reads index position 0 ('Apple') using standard bracket access.

Line 5: Logs 'Apple' directly to browser debugger diagnostics.

Runnable Code Examples

Example 1: Creating Array & Index Access

Set up a simple array literal and retrieve items using zero-indexed positions.

javascript
const members = ["Asha", "Bishal", "Carla"];
console.log(members[0]);
console.log(members[members.length - 1]);
expected console output
Asha Carla
Breakdown:

Retrieves the first element using index 0 and the final element using length subtraction.

Example 2: Modifying Array Elements

Change existing array contents by reassigning values to specific indexes.

javascript
const prices = [100, 200, 300];
prices[1] = 250; // Change index 1 value
console.log(prices);
expected console output
[100, 250, 300]
Breakdown:

Overwrites the value at index position 1 from 200 to 250 in-place.

Example 3: Adding Elements (push & length)

Append items to the end of the array using built-in push methods or length offsets.

javascript
const stack = ["HTML", "CSS"];
stack.push("JS");
stack[stack.length] = "TS";
console.log(stack);
expected console output
['HTML', 'CSS', 'JS', 'TS']
Breakdown:

Appends two items. push() is the standard method, whereas length-assignment utilizes current offsets.

Example 4: Recognizing arrays (Array.isArray)

Verify if a variable is an array using built-in methods.

javascript
const grades = [90, 85];
console.log(Array.isArray(grades));
console.log(grades instanceof Array);
expected console output
true true
Breakdown:

Since typeof array returns 'object', Array.isArray and instanceof are key diagnostic utilities.

Example 5: Nested Array Structures

Create multidimensional arrays containing nested list variables.

javascript
const grid = [[1, 2], [3, 4]];
console.log(grid[1][0]); // Row 1, Col 0
expected console output
3
Breakdown:

Accesses index 1 of the parent array (which is the array [3, 4]), then grabs index 0 of that array.

Real-world Use Cases

  • 1

    Storing product records fetched from database endpoints before rendering product grids.

  • 2

    Managing shopping cart items, where each item contains product ID, size, and quantities.

  • 3

    Keeping track of user-selected filters on search dashboards.

  • 4

    Queuing background jobs in asynchronous event systems.

  • 5

    Creating datasets for dashboard charts utilizing libraries like Recharts.

Coding Exercises

1

Exercise Challenge

Declare an empty array literal named 'cart'.

2

Exercise Challenge

Access the second item inside the array 'const colors = ['red', 'blue', 'green']'.

3

Exercise Challenge

Append the string 'gold' to the array 'const ranks = ['silver']' using the push method.

4

Exercise Challenge

Find the length of the array 'const list = [10, 20, 30]'.

5

Exercise Challenge

Verify if 'const x = {}' is an array using Array.isArray.

6

Exercise Challenge

Get the first element of 'const items = ['First', 'Second']'.

7

Exercise Challenge

Override the third element of 'const prices = [10, 20, 30]' to be 40.

8

Exercise Challenge

Check if the array 'const items = ['Apple']' is an instance of Array.

9

Exercise Challenge

Append an element to array 'list' by assigning it to index 'list.length'.

10

Exercise Challenge

Create an array containing numbers 1, 2, and 3 using literal notation.

Practice Tasks Checklist

1Create an array containing 5 city names and print the first and final cities.
2Assign an array using const and mutate the second index value to verify mutations work.
3Add a new city name to your cities array utilizing the push method.
4Verify if a test variable is an array using Array.isArray and log the result.
5Access the element 99 in this nested array structure: const numbers = [[1, 2], [99, 100]].
6Write a loop that prints every city in your array to the console.
7Create a sparse array by assigning index 10 and log the array to see the empty slots.
8Create a shopping list array, access its length property, and log the length.
9Initialize an array with 3 elements, delete the second element using `delete`, and log the array to see the resulting undefined hole.
10Demonstrate why copying an array via `const copy = original` is a reference copy by mutating `copy` and checking `original`.

JavaScript Arrays Quiz Challenges

1

Quiz Challenge

What index does a JavaScript array start at?

2

Quiz Challenge

How do you check if a variable is an array in JavaScript?

3

Quiz Challenge

What is returned when you query the typeof of an array?

4

Quiz Challenge

Which property returns the number of elements inside an array?

5

Quiz Challenge

Which of the following safely appends an element to the end of the array?

6

Quiz Challenge

What is created when you call the constructor new Array(5)?

7

Quiz Challenge

Can JavaScript arrays store elements of different data types in the same list?

8

Quiz Challenge

How do you access the last element in an array named 'list'?

9

Quiz Challenge

What is an associative array in JavaScript?

10

Quiz Challenge

What happens if you delete an element from an array using 'delete arr[1]'?

Technical Interview Q&As

1How do you distinguish an array from a regular object?

Model Answer:

Since `typeof array` returns 'object', you must use `Array.isArray(variable)` or `variable instanceof Array` to reliably confirm if a variable is an array.
2What is the danger of using new Array() with a single numeric argument?

Model Answer:

If you call `new Array(5)`, it does not create an array containing [5]. Instead, it creates an empty array with a length of 5 containing undefined slots (empty holes).
3What are the characteristics of associative arrays in JavaScript?

Model Answer:

JavaScript does not support associative arrays with string indexes. If you assign items using string indexes, JS converts the array into a regular object, and all array methods (like push, length) cease to function on those entries.
4How do you find the last element in a JavaScript array?

Model Answer:

You can find it by querying index length minus one, such as `arr[arr.length - 1]`, or by utilizing the modern array method `arr.at(-1)`.
5What is the difference between an array and an object?

Model Answer:

Arrays use ordered, zero-indexed numerical positions to store values. Objects use unordered, key-value string pairs to hold properties. Use arrays for lists of similar items and objects for singular entities with attributes.
6Does const prevent mutating array elements?

Model Answer:

No. `const` locks the variable's memory reference, meaning you cannot reassign the variable to a new array. However, you are free to add, delete, or update elements within the array.
7How do you check if an element exists in an array?

Model Answer:

You can use `arr.includes(element)`, which returns true or false, or `arr.indexOf(element)`, which returns the element's index or -1 if it is missing.
8What are empty slots in sparse arrays?

Model Answer:

Empty slots occur when you insert an element at an index far beyond the current length (e.g. inserting at index 10 on a 3-element array). The intermediate slots are empty and return undefined, which can break array methods.
9Can an array contain multiple data types?

Model Answer:

Yes, JavaScript arrays are weakly-typed and can hold a mix of strings, numbers, booleans, objects, arrays, and functions in the same list.
10What is a multidimensional array?

Model Answer:

A multidimensional array is an array that contains other arrays as its elements, creating grid-like structures accessed via chained indexes like `arr[0][1]`.

Related Lessons

Frequently Asked Questions