HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaScriptVariables (let / const)Data TypesOperatorsStringsArraysObjectsConditions (if / else)Loops (for / while)FunctionsArrow Functions (=>)Array Methods (map / filter / reduce)
REFERENCE
📖 Overview
🖥️ Output & Console
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Object
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
JavaScript›Arrays

Arrays

Creating arrays, accessing elements, adding/removing (push/pop), and iterating with loops.

Simple enough for a 5-year-old to understand

Create an array and access elements

Example code
1
const colors = ["red", "purple", "green"];
An array with three elements.
DataAn array with three elements.
2
console.log(colors[0]);
First element: get (starts from 0!).
Output / InputFirst element: get (starts from 0!).
3
console.log(colors.length);
Number of elements: 3
Output / InputNumber of elements: 3
DataOutput / Input
💡 Hint: The first element is arr[0]; counting starts from 0.

Adding and removing

Example code
1
const basket = ["apple"];
Single element.
DataSingle element.
2
basket.push("pear");
Adds to the end.
CodeAdds to the end.
3
console.log(basket);
[ 'apple', 'pear' ]
Output / Input[ 'apple', 'pear' ]
DataCodeOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.What is a[0] in the array const a = ["x", "y"]?

About this topic

An array is a structure that holds multiple values in an ordered way, and it is the most commonly used data structure in JavaScript. Records returned from a server, elements on a page, products in a cart — they all arrive as arrays and are processed as arrays.

JavaScript arrays are flexible: their length is dynamic, they can hold different types together, and they can even contain other arrays inside. This flexibility provides convenience but requires attention — the language does not guarantee that all elements of an array are of the same type.

What you will learn

  • Creating arrays and accessing them by index
  • Adding and removing elements with push, pop, shift, and unshift
  • The difference between splice and slice
  • Iterating over arrays with loops and for-of
  • Using destructuring assignment and the spread operator
  • Why copying arrays requires special attention

When to use?

You use an array for any dataset where order matters and the count can change. Displaying a list on screen, processing an API response, accumulating user selections are all array tasks.

If you need access by key, an object is more appropriate; if you need unique values, a Set is better; if you need key-value mapping, a Map is more suitable.

Common mistakes

Wrong

const a = [1, 2, 3];
const b = a;
b.push(4);
console.log(a.length);

The equals sign does not copy the array; it gives the same array a second name. Elements you add via b will also appear in a, and the length comes out as 4. This is the most common reference error.

Correct

const a = [1, 2, 3];
const b = [...a];
b.push(4);
console.log(a.length);

Wrong

const items = [1, 2, 3];
items[5] = 9;
console.log(items.length);

JavaScript does not check array boundaries; writing to a non-existent index grows the array and leaves empty slots in between. The length becomes 6, and you will encounter undefined values in loops.

Correct

const items = [1, 2, 3];
items.push(9);
console.log(items.length);

Wrong

const nums = [1, 2, 3, 4];
for (const n of nums) {
  if (n % 2 === 0) nums.splice(nums.indexOf(n), 1);
}

Deleting an element from the array you are iterating over shifts the indices; the loop skips some elements and the result is wrong. You won't get an error message, it fails silently.

Correct

let nums = [1, 2, 3, 4];
nums = nums.filter((n) => n % 2 !== 0);

Frequently asked questions

What is the difference between slice and splice?

slice does not touch the original array, it returns a copied slice. splice, on the other hand, modifies the array IN PLACE — it deletes or adds elements. Since their names are similar, they get mixed up; use slice if you want to protect the original data.

How can I safely copy an array?

With the spread operator or slice. However, this is a shallow copy: if there are objects inside the array, those objects are still shared. To completely separate nested structures, you need to use structuredClone.

Should I use a for loop or for-of?

If you only need the elements, for-of is more readable. If you also need the index, you can get both together with entries or use a classic for loop. for-in is used for objects, but using for-in on arrays is not recommended as order is not guaranteed.

Summary

An array is JavaScript's most used data structure, managed with methods like push and filter. Two main pitfalls: the equals sign does not create a copy, and splice modifies the array in place.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code