ARRAYS IN JAVASCRIPT
Arrays are one of the most important topics in JavaScript because they help us store and work with many values together.
You will use arrays in lists of products, users, messages, numbers, tags, search results, API data, and front-end rendering.
1. What is an array?
An array is an ordered collection of elements.
It is used to store many values in one place.
const planets = ["Earth", "Mars", "Venus"];
const numbers = [1, 2, 3, 4, 5];
planetsstores several strings.numbersstores several numbers.
Diagram 1. Array as a box with many positions
Array
│
├─ position 0 → "Earth"
├─ position 1 → "Mars"
└─ position 2 → "Venus"
Explanation
An array is like one container with many numbered positions inside it. Each value has its own place.
2. Array literal
To create an array in JavaScript, we use square brackets [] and values separated by commas.
const fruits = ["apple", "banana", "orange"];
This is called an array literal.
Diagram 2. Array literal structure
[ value1, value2, value3 ]
1. [ ] → tells JavaScript this is an array
2. values go inside
3. commas separate the values
Explanation
This is the basic way to create arrays in JavaScript.
3. Arrays can contain different data types
Usually, arrays store similar values, but JavaScript does not require that.
const mixed = ["apple", 10, true];
"apple"is a string.10is a number.trueis a Boolean.
Diagram 3. Mixed array
mixed
│
├─ index 0 → "apple"
├─ index 1 → 10
└─ index 2 → true
Explanation
JavaScript allows mixed arrays, but in real projects it is often clearer when one array stores similar kinds of data.
4. Array indexing
An array is ordered. That means each element has a position number called an index.
Array indexing starts from 0, not from 1.
- First element → index
0. - Second element → index
1. - Third element → index
2.
Diagram 4. Indexes in an array
["Earth", "Mars", "Venus"]
Index: 0 1 2
Value: "Earth" "Mars" "Venus"
Explanation
This is exactly the same idea as string indexing. The first position is always 0.
5. Accessing array elements
To get an element from an array, use square brackets with the index.
arrayName[index]
const planets = ["Earth", "Mars", "Venus"];
console.log(planets[0]); // "Earth"
console.log(planets[1]); // "Mars"
console.log(planets[2]); // "Venus"
Diagram 5. Accessing array values
planets[0] → "Earth"
planets[1] → "Mars"
planets[2] → "Venus"
Explanation
JavaScript looks inside the array and returns the value at the position you ask for.
6. Saving an array element into a variable
The result of accessing an element can be stored in another variable.
const planets = ["Earth", "Mars", "Venus"];
const firstElement = planets[0];
console.log(firstElement); // "Earth"
Diagram 6. Taking one value out of an array
planets[0]
↓
"Earth"
↓
firstElement = "Earth"
Explanation
This is useful when you want to work with one specific value later.
7. Accessing a non-existing index
If you try to access an index that does not exist, JavaScript returns undefined.
const planets = ["Earth", "Mars", "Venus"];
console.log(planets[3]); // undefined
console.log(planets[999]); // undefined
Diagram 7. Missing index
["Earth", "Mars", "Venus"]
Existing indexes:
0, 1, 2
planets[3] → undefined
planets[999] → undefined
Explanation
If there is no value at that position, JavaScript cannot return a real element, so it returns undefined.
8. Reassigning an array element
You can change an element in an array by accessing it by index and giving it a new value.
const planets = ["Earth", "Mars", "Venus", "Uranus"];
planets[0] = "Jupiter";
planets[2] = "Neptune";
console.log(planets); // ["Jupiter", "Mars", "Neptune", "Uranus"]
Diagram 8. Changing elements by index
Before:
["Earth", "Mars", "Venus", "Uranus"]
Change:
index 0 → "Jupiter"
index 2 → "Neptune"
After:
["Jupiter", "Mars", "Neptune", "Uranus"]
Explanation
We do not replace the whole array variable. We only replace some values inside the array.
9. Important idea: the variable still stores an array
The variable still contains an array. Only the contents changed.
const planets = ["Earth", "Mars", "Venus", "Uranus"];
planets[0] = "Jupiter";
Diagram 9. What really changes
Variable name:
planets
Still stores:
an array
Changed:
values inside the array
Explanation
This is why const arrays can still have changed elements. The variable still points to the same array.
10. Array length
Arrays have a property called length. It tells you how many elements are in the array.
const planets = ["Earth", "Mars", "Venus"];
console.log(planets.length); // 3
Diagram 10. length property
["Earth", "Mars", "Venus"]
Elements count = 3
planets.length → 3
Explanation
length is very important because it lets you know the current size of the array.
11. Using length in conditions
const planets = ["Earth", "Mars", "Venus"];
if (planets.length >= 3) {
console.log("3 or more elements");
} else {
console.log("less than 3 elements");
}
Diagram 11. Checking array size
planets.length = 3
Check:
3 >= 3
↓
true
↓
"3 or more elements"
Explanation
This is useful when your program depends on how many items are stored.
12. Index of the last element
The last element of an array does not have a fixed index, because arrays can have different lengths.
array.length - 1
const planets = ["Earth", "Mars", "Venus"];
const lastElementIndex = planets.length - 1;
console.log(planets[lastElementIndex]); // "Venus"
Diagram 12. Last index formula
Array: ["Earth", "Mars", "Venus"]
length = 3
last index = 3 - 1 = 2
planets[2] → "Venus"
Explanation
Because indexing starts at 0, the last index is always one less than the length.
13. Short version for last element
You do not need a separate variable if you do not want one.
const planets = ["Earth", "Mars", "Venus"];
console.log(planets[planets.length - 1]); // "Venus"
Diagram 13. Direct access to the last element
planets[planets.length - 1]
↓
last index
Explanation
This is a common JavaScript pattern.
14. Arrays and memory: value vs reference
There are two big groups of data: primitive values and complex values.
Primitive values include numbers, strings, Booleans, null, and undefined. They are copied by value.
Arrays are complex values. They are assigned by reference.
Diagram 14. Two types of assignment
Primitive values
→ copied by value
Arrays and other complex data
→ assigned by reference
Explanation
This difference is very important because it changes how variables behave.
15. Assignment by value
When a primitive value is copied, JavaScript creates a separate independent copy.
let a = 5;
let b = a;
console.log(a); // 5
console.log(b); // 5
a = 10;
console.log(a); // 10
console.log(b); // 5
Diagram 15. Copy by value
a = 5
b = a
Now:
a → 5
b → 5
Change a to 10
After:
a → 10
b → 5
Explanation
b does not change because it has its own separate copy.
16. Assignment by reference with arrays
When you assign one array variable to another, JavaScript does not create a new array automatically.
Instead, both variables point to the same array in memory.
const a = ["Aaron", "Benjamin"];
const b = a;
console.log(a); // ["Aaron", "Benjamin"]
console.log(b); // ["Aaron", "Benjamin"]
Diagram 16. Copy by reference
One array in memory:
["Aaron", "Benjamin"]
a ─────────────┐
├→ same array
b ─────────────┘
Explanation
a and b do not hold two different arrays. They both point to the same one.
17. Changing the array through one variable
const a = ["Aaron", "Benjamin"];
const b = a;
a[1] = "Jacob";
console.log(a); // ["Aaron", "Jacob"]
console.log(b); // ["Aaron", "Jacob"]
Diagram 17. Changing through a
Before:
a → ["Aaron", "Benjamin"]
b → ["Aaron", "Benjamin"]
Change:
a[1] = "Jacob"
After:
a → ["Aaron", "Jacob"]
b → ["Aaron", "Jacob"]
Explanation
Because both variables point to the same array, a change through a is also visible through b.
18. Changing the array through the other variable
const a = ["Aaron", "Benjamin"];
const b = a;
a[1] = "Jacob";
b[0] = "Samuel";
console.log(a); // ["Samuel", "Jacob"]
console.log(b); // ["Samuel", "Jacob"]
Diagram 18. Changing through b
Shared array:
["Aaron", "Benjamin"]
a[1] = "Jacob"
b[0] = "Samuel"
Final shared array:
["Samuel", "Jacob"]
Explanation
It does not matter which variable you use. Both change the same shared array.
19. Two different arrays are never strictly equal
Even if two arrays have exactly the same elements, they are still different arrays in memory.
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
console.log(arr1 === arr2); // false
console.log([] === []); // false
Diagram 19. Same content, different arrays
arr1 → [1, 2, 3]
arr2 → [1, 2, 3]
Content looks the same
But references are different
arr1 === arr2 → false
Explanation
=== for arrays checks whether the references are the same, not whether the inside values look the same.
20. When array references are equal
If two variables point to the same array, then === gives true.
const arr1 = [1, 2, 3];
const arr2 = arr1;
console.log(arr1 === arr2); // true
Diagram 20. Same reference
One array:
[1, 2, 3]
arr1 ─────┐
├→ same array
arr2 ─────┘
arr1 === arr2 → true
Explanation
This time both variables point to exactly the same array in memory.
21. Read this code example
const arr1 = [1, 2, 3];
const arr2 = arr1;
arr1[1] = 1;
arr2[2] = 1;
Both arrays become [1, 1, 1].
arr2points to the same array asarr1.arr1[1] = 1changes the second element.arr2[2] = 1changes the third element.
Diagram 21. Step by step for the shared array
Start:
[1, 2, 3]
arr1[1] = 1
↓
[1, 1, 3]
arr2[2] = 1
↓
[1, 1, 1]
Both arr1 and arr2 see:
[1, 1, 1]
Explanation
This is a perfect example of assignment by reference.
22. Type conversion of arrays
Arrays can also be converted to other types.
- Array → string.
- Array → number.
- Array → Boolean.
Diagram 22. Array conversions
Array
│
├─ to String
├─ to Number
└─ to Boolean
Explanation
Just like other values in JavaScript, arrays can be converted depending on the operation.
23. Array to string
When an array becomes a string, its elements are joined with commas.
const array = [1, true, "Benjamin"];
console.log(String(array)); // "1,true,Benjamin"
console.log(array + "5"); // "1,true,Poly5"
Diagram 23. Array → string
[1, true, "Benjamin"]
↓
"1,true,Benjamin"
Explanation
JavaScript joins the elements into one comma-separated string.
24. Array to number
When converting an array to a number, JavaScript first converts it to a string, then tries to convert that string to a number.
console.log(Number([])); // 0
console.log(Number([1])); // 1
console.log(Number([1, 2, 3])); // NaN
Diagram 24. Array → number in two steps
Step 1: array → string
Step 2: string → number
Explanation
This two-step process explains the results.
25. Why these results happen
Number([])
[] → "" → 0
Number([1])
[1] → "1" → 1
Number([1, 2, 3])
[1, 2, 3] → "1,2,3" → NaN
"1,2,3" is not a valid normal number string.
Diagram 25. Array to number examples
[] → "" → 0
[1] → "1" → 1
[1,2,3] → "1,2,3" → NaN
Explanation
The more elements there are, the more likely the final string cannot become a valid number.
26. Array to Boolean
When converting an array to Boolean, any array becomes true. Even an empty array [] becomes true.
const emptyArray = [];
const nonEmptyArray = [1, 2, 3];
console.log(Boolean(emptyArray)); // true
console.log(Boolean(nonEmptyArray)); // true
Diagram 26. Array → Boolean
[] → true
[1,2,3] → true
[false] → true
Explanation
This surprises many beginners. Even an empty array is truthy.
27. Arrays in if
const emptyArray = [];
if (emptyArray) {
console.log("if is in progress");
} else {
console.log("else is not performed");
}
Output:
if is in progress
The if block runs because [] is truthy.
Diagram 27. Empty array in condition
emptyArray = []
↓
Boolean([])
↓
true
↓
if block runs
Explanation
An empty array is not falsy. This is a very important JavaScript detail.
28. Non-empty array in if
const nonEmptyArray = [1, 2, 3];
if (nonEmptyArray) {
console.log("if is in progress");
} else {
console.log("else is not performed");
}
Output:
if is in progress
Diagram 28. Non-empty array in condition
[1, 2, 3]
↓
true
↓
if block runs
Explanation
All arrays are truthy in Boolean conversion.
29. Read this code example
const array = [false];
const result = array ? "A" : "B";
The result is "A" because [false] is still an array, and any array is truthy.
The value inside the array does not matter for Boolean conversion of the array itself.
Diagram 29. Why [false] still gives "A"
[false]
↓
array exists
↓
Boolean([false]) = true
↓
result = "A"
Explanation
false alone is falsy, but [false] is an array, and arrays are truthy.
30. Practical examples
Example 1. Array of users
const users = ["Sarah", "Nikita", "Isaac"];
console.log(users[1]); // "Nikita"
Example 2. Changing one value
const scores = [10, 20, 30];
scores[1] = 50;
console.log(scores); // [10, 50, 30]
Example 3. Last element
const colors = ["red", "green", "blue"];
console.log(colors[colors.length - 1]); // "blue"
Example 4. Shared reference
const a = ["x", "y"];
const b = a;
b[0] = "z";
console.log(a); // ["z", "y"]
console.log(b); // ["z", "y"]
Diagram 30. Practical array patterns
Get first element:
array[0]
Get last element:
array[array.length - 1]
Change element:
array[index] = newValue
Explanation
These are some of the most common array patterns you will use.
31. Common beginner mistakes
Mistake 1. Thinking indexing starts from 1
planets[1] // expecting first element
Actually, planets[0] is the first element.
Mistake 2. Forgetting that missing indexes give undefined
const arr = ["a", "b"];
console.log(arr[5]); // undefined
Mistake 3. Thinking copied array variables are independent
const a = [1, 2];
const b = a;
These are not two separate arrays.
Mistake 4. Thinking [] is falsy
Boolean([]) // true
Mistake 5. Thinking equal-looking arrays are strictly equal
[1, 2, 3] === [1, 2, 3] // false
Diagram 31. Common mistakes
1. First index is 0, not 1
2. Missing index gives undefined
3. Arrays are assigned by reference
4. [] is truthy
5. Same-looking arrays are not the same reference
Explanation
These are some of the most important array mistakes to avoid.
32. Quick summary
- Array: an ordered collection of values.
- Index: the position number of an element.
- First index: always
0. - Accessing an element: use
array[index]. - Changing an element: use
array[index] = newValue. length: number of elements in the array.- Last index:
array.length - 1. - Primitive assignment: copied by value.
- Array assignment: assigned by reference.
- Array to string: elements join with commas.
- Array to number: first becomes string, then number.
- Array to Boolean: any array is
true.
Diagram 32. Final map of arrays
Arrays
│
├─ creation
├─ indexing
├─ access
├─ reassignment
├─ length
├─ last element
├─ value vs reference
└─ type conversion
├─ string
├─ number
└─ Boolean
Explanation
This is the full picture of the beginner array topic.
33. Revision block
1. An array stores many values in order
2. Arrays use square brackets []
3. The first index is 0
4. Access elements with array[index]
5. Missing indexes return undefined
6. Array elements can be changed by index
7. array.length gives the number of elements
8. The last index is array.length - 1
9. Primitives are copied by value
10. Arrays are assigned by reference
11. Two different arrays are never strictly equal
12. Any array is truthy
13. Array to string joins elements with commas
14. Array to number first goes through string conversion
34. Final conclusion
Arrays are one of the foundations of JavaScript.
If you understand how to create arrays, how indexing works, how to access values, how to change elements, how length works, how to get the last element, how assignment by reference works, and how array type conversion works, then you already have a strong base for working with collections of data.
Arrays are used everywhere in full stack development: rendering lists, storing results from APIs, handling products and users, working with tables, and filtering or searching data.