This content originally appeared on DEV Community and was authored by Keshav Kumar
Arrays are a fundamental part of JavaScript, used for storing and manipulating collections of data. Whether you’re a beginner or looking to deepen your understanding, this guide covers key concepts, common pitfalls, and advanced methods through a series of questions and answers.
From basic array operations to advanced methods like reduce()
, flatMap()
, and typed arrays
, this document provides a comprehensive learning path to master arrays in JavaScript.
Let’s dive in!
1. How can we declare an array in JavaScript?
let arr = [1, 2, 3]; // Using square brackets
let arr2 = new Array(1, 2, 3); // Using Array constructor
Key Differences:
The bracket notation
[]
is the preferred and most commonly used method.The
new Array()
constructor can sometimes behave unexpectedly. For example,new Array(5)
creates an array with five empty slots, not an array containing the number5
.
2. What is the difference between an array and an object in JavaScript?
Key Differences between Arrays and Objects in JavaScript:
Objects
- Store data in key-value pairs
{ key: value }
. - Keys are usually strings (or symbols).
- Typically used for structured data like a user profile. Example:
let user = { name: "John", age: 25, greet: function() { console.log("Hello!"); } };
Arrays
- A special type of object optimized for storing ordered collections.
- Indexed using numeric indices (0, 1, 2, …).
- Have built-in methods like
.push()
,.pop()
,.map()
, etc. Example:
let numbers = [10, 20, 30];
console.log(numbers[0]); // 10
Key Differences:
- Objects are unordered collections, while arrays maintain a specific order.
- Arrays are faster for iterating with loops, while objects are better for associative data storage.
3. How can you access the third element of an array?
- Arrays in JavaScript are zero-indexed, meaning the first element is at index
0
, the second at1
, and so on.
let arr = [10, 20, 30];
console.log(arr[2]);
4.What happens if you access an index that is out of bounds in an array?
When you access an index greater than the last index in an array, JavaScript returns undefined
:
let arr = [1, 2, 3];
console.log(arr[10]); // undefined
This does not throw an error, unlike some other languages (e.g., Python
).
Fun Fact: You can assign a value to an out-of-bounds index, and JavaScript will expand the array, filling the missing spots with
empty
values:
let arr = [1, 2, 3];
arr[5] = 10;
console.log(arr); // [1, 2, 3, empty × 2, 10]
Notice the "empty × 2"
slots instead of undefined
.
5. How do you add an element to the end of an array? What about the beginning?
To add an element to the end of an array:
Use .push()
, which appends elements to the end of the array.
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
Incorrect:
arr.push(0, "5")
does not add "5"
at index 0
.
Correct:
let arr = [1, 2, 3];
arr.push(0, "5");
console.log(arr); // [1, 2, 3, 0, "5"] (adds both to the end)
To add an element to the beginning of an array:
Use .unshift()
, which inserts elements at the start.
let arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
Key Difference:
-
.push()
adds to the end. -
.unshift()
adds to the beginning.
6. What are the differences between .push()
, .pop()
, .shift()
, and .unshift()
?
1.
.push(value)
→ Adds value(s) to the end of the array
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
2.
.pop()
→ Removes the last element and returns it
let arr = [1, 2, 3];
let last = arr.pop();
console.log(arr); // [1, 2]
console.log(last); // 3 (returns the removed element)
Incorrect: You mentioned
.pop()
deletes a value at a specific index—but that’s not true. It only removes the last element.
3.
.shift()
→ Removes the first element and returns it
let arr = [1, 2, 3];
let first = arr.shift();
console.log(arr); // [2, 3]
console.log(first); // 1 (returns the removed element)
Incorrect: You said
.shift()
adds values in the middle or at a specific index—that’s incorrect.
4.
.unshift(value)
→ Adds value(s) to the beginning of the array
let arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
Key Differences Summary:
Method | Action | Position | Returns |
---|---|---|---|
.push() |
Add element(s) | End | New array length |
.pop() |
Remove element | End | Removed element |
.shift() |
Remove element | Start | Removed element |
.unshift() |
Add element(s) | Start | New array length |
7. How do you loop through an array using different looping methods? (e.g., for
, forEach
, map
)
1. Using a
for
loop
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
2. Using a
.forEach()
Implementation:
arr.forEach((element) => {
console.log(element);
});
forEach()
iterates through each element directly, without needing an index.
3. Using a
.map()
Implementation:
arr.map((element) => {
console.log(element); // ✅ Correct usage
return element * 2; // Example of modifying elements
});
If you use
.map()
, it should return a new array.
Final Summary:
Method | Purpose | Returns a new array? | Correct Usage |
---|---|---|---|
for loop |
Standard iteration | ![]() |
![]() arr[i]
|
.forEach() |
Loops through elements | ![]() |
![]() console.log(element)
|
.map() |
Transforms elements | ![]() |
![]() return element * 2
|
8. How does JavaScript handle sparse arrays (arrays with missing elements)?
What is a Sparse Array?
A sparse array in JavaScript is an array that has empty (missing) slots instead of actual values. These slots are also called “holes”.
How Are Sparse Arrays Created?
1⃣ By manually skipping indices:
let sparseArr = [1, , 3, , 5];
console.log(sparseArr); // [1, empty, 3, empty, 5]
2⃣ By setting an index out of bounds:
let arr = [1, 2, 3];
arr[5] = 6; // Creates empty slots at index 3 and 4
console.log(arr); // [1, 2, 3, empty × 2, 6]
How Does JavaScript Handle Sparse Arrays?
1⃣ Accessing Empty Slots Returns undefined
:
console.log(sparseArr[1]); // undefined (but the slot exists!)
Note: The slot is not null or 0, it’s just an empty hole.
2⃣ Looping Over a Sparse Array:
- Some methods skip empty slots:
sparseArr.forEach((val) => console.log(val));
// Output: 1, 3, 5 (skips empty slots)
- Others treat empty slots as
undefined
:
console.log(sparseArr.map((x) => x * 2));
// Output: [2, empty, 6, empty, 10]
3⃣ Converting a Sparse Array into a Dense One:
You can use .filter()
to remove empty slots:
let denseArr = sparseArr.filter(() => true);
console.log(denseArr); // [1, 3, 5]
Key Takeaways
JavaScript allows sparse arrays but treats them differently than normal arrays.
Empty slots exist but don’t behave like
undefined
values.
Some methods (like
forEach()
) skip empty slots, while others (like map()
) don’t.
To “fix” a sparse array, use
.filter(() => true)
to remove holes.
9. What is the difference between .map()
, .filter()
, and .reduce()
?
1. .map()
→ Transforms Each Element
- Loops through an array and returns a new array where each element is transformed based on the callback function.
- The original array is not modified.
Example:
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
Each element is modified and stored in a new array.
2. .filter()
→ Filters Elements Based on a Condition
- Loops through an array and returns a new array containing only elements that pass a true/false test (predicate function).
- The original array is not modified.
Example:
let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
Only elements that pass the condition
(num % 2 === 0)
are included.
3. .reduce() → Reduces an Array to a Single Value
- Loops through an array and accumulates (reduces) the values into a single output.
- Requires a callback function with two parameters:
- Accumulator → Stores the running total
- Current element → The value being processed
Example: Summing an Array
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
Starts with 0 (initial value) and adds each element one by one:
(0 + 1) → (1 + 2) → (3 + 3) → (6 + 4) → (10 + 5) = 15
Another Example: Finding the Maximum Value in an Array
let max = numbers.reduce((acc, num) => (num > acc ? num : acc), numbers[0]);
console.log(max); // 5
Keeps the largest number as it loops through.
Key Differences Summary
Method | Purpose | Returns a New Array? | Example Usage |
---|---|---|---|
.map() |
Transforms elements | ![]() |
Multiply all values by 2 |
.filter() |
Keeps elements that match a condition | ![]() |
Keep only even numbers |
.reduce() |
Combines elements into a single value | ![]() |
Find sum, max, min, etc. |
Final Thought:
- Use
.map()
when you want to transform each element. - Use
.filter()
when you want to remove unwanted elements. - Use
.reduce()
when you need to calculate a single value from the array.
10. How can you find the index of a specific element in an array? What happens if the element is not found?
Finding the Index of an Element in an Array
1. Using .indexOf(value)
- Returns the index of the first occurrence of the specified element.
- Returns
-1
if the element is not found.
Example:
let arr = [10, 20, 30, 40, 50];
console.log(arr.indexOf(30)); // 2 (found at index 2)
console.log(arr.indexOf(100)); // -1 (not found)
2. Using .lastIndexOf(value)
- Works like
.indexOf()
, but searches from the end instead of the start.
Example:
let arr = [10, 20, 30, 40, 30, 50];
console.log(arr.lastIndexOf(30)); // 4 (last occurrence at index 4)
console.log(arr.lastIndexOf(100)); // -1 (not found)
3. Using .findIndex(callback)
- Returns the index of the first element that matches a condition.
- If no match is found, it returns
-1
. - Useful when searching objects or complex conditions.
Example:
let numbers = [10, 20, 30, 40, 50];
let index = numbers.findIndex(num => num > 25);
console.log(index); // 2 (30 is the first number > 25)
What If the Element Is Not Found?
- All three methods (
indexOf()
,lastIndexOf()
,findIndex()
) return-1
if the element is not in the array.
Example:
let arr = [1, 2, 3];
console.log(arr.indexOf(10)); // -1 (not found)
Quick Summary
Method | Returns | Searches By | Example |
---|---|---|---|
.indexOf(value) |
First matching index (or -1 if not found) |
Exact match |
arr.indexOf(3) → 2
|
.lastIndexOf(value) |
Last matching index (or -1 if not found) |
Exact match (from end) |
arr.lastIndexOf(3) → 4
|
.findIndex(callback) |
First matching index (or -1 if not found) |
Custom condition | arr.findIndex(x => x > 25) |
11. How do you remove an element from an array by its value, not its index?
1. Using .splice()
(Best Method)
-
.splice(index, howMany)
removes elements at a specific index.
Steps:
1⃣ Find the index of the element using .indexOf(value)
.
2⃣ Remove it using .splice(index, 1)
.
Example:
let arr = [10, 20, 30, 40, 50];
let index = arr.indexOf(30); // Find index of 30
if (index !== -1) {
arr.splice(index, 1); // Remove 1 element at the found index
}
console.log(arr); // [10, 20, 40, 50]
This works for single occurrences of a value.
2. Using .filter()
(If You Need a New Array)
- If you want to create a new array without modifying the original one, use
.filter()
.
Example:
let arr = [10, 20, 30, 40, 50];
let newArr = arr.filter(num => num !== 30); // Removes 30
console.log(newArr); // [10, 20, 40, 50]
This keeps all elements except 30 without modifying
arr
.
3. Using .findIndex()
+ .splice()
(For Complex Conditions)
- Use
.findIndex()
if you need to find and remove an object or complex value.
Example:
let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
let index = people.findIndex(person => person.name === "Bob");
if (index !== -1) {
people.splice(index, 1); // Removes Bob
}
console.log(people);
// [
// { name: "Alice", age: 25 },
// { name: "Charlie", age: 35 }
// ]
Works when searching for objects or specific conditions!
Quick Summary
Method | Modifies Original? | Works on | Example |
---|---|---|---|
.splice(index, 1) |
![]() |
Single value | arr.splice(arr.indexOf(30), 1) |
.filter(x => x !== value) |
![]() |
Multiple values | arr.filter(num => num !== 30) |
.findIndex() + .splice() |
![]() |
Complex objects | arr.findIndex(obj => obj.name === "Bob") |
12. What is the difference between shallow copy and deep copy of an array in JavaScript? How can you create each type?
Shallow Copy vs. Deep Copy
What is a Shallow Copy?
- A shallow copy creates a new array but still shares references to the original object’s nested data.
- Changes in nested objects affect both copies!
- Only the top-level elements are copied, not deeply nested objects.
Example:
let original = [{ name: "Alice" }, { name: "Bob" }];
let shallowCopy = [...original]; // Spread operator (shallow copy)
// Modify the nested object
shallowCopy[0].name = "Eve";
console.log(original[0].name); // "Eve" (Changes original!)
console.log(shallowCopy[0].name); // "Eve" (Same reference)
Even though we copied the array, the objects inside still share the same reference.
What is a Deep Copy?
- A deep copy creates a completely independent copy of an array, including nested objects.
- Changes in the copied array do NOT affect the original.
- All nested data is fully cloned.
Example Using JSON.parse(JSON.stringify())
:
let original = [{ name: "Alice" }, { name: "Bob" }];
let deepCopy = JSON.parse(JSON.stringify(original)); // Deep copy
// Modify the nested object in the copy
deepCopy[0].name = "Eve";
console.log(original[0].name); // "Alice" (Original remains unchanged)
console.log(deepCopy[0].name); // "Eve" (Independent copy)
Now the original and copy are completely separate!
How to Create Each Type?
Copy Type | Creates a New Array? | Nested Objects Shared? | Methods |
---|---|---|---|
Shallow Copy | ![]() |
![]() |
slice() , [...arr] , Array.from(arr) , .map(x => x)
|
Deep Copy | ![]() |
![]() |
JSON.parse(JSON.stringify(arr)) , structuredClone(arr)
|
When to Use Each?
- Use a shallow copy if you only need a new array but don’t care about nested objects.
-
Use a deep copy if modifying the copied array should not affect the original.
Bonus: Using
structuredClone()
for Deep Copy (Modern Way) structuredClone()
is the best way to deep-copy complex objects in modern JavaScript.
Example:
let deepCopy = structuredClone(original);
Works on nested objects and doesn’t have issues with dates or functions like
JSON.parse()
.
13. How can you merge two or more arrays in JavaScript? What happens if the arrays contain objects?
Ways to Merge Arrays in JavaScript
1⃣ Using the Spread Operator (...)
(Best Method)
- The spread operator (
...
) expands elements of an array into another array.
Example:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = [...arr1, ...arr2];
console.log(newArr); // [1, 2, 3, 4, 5, 6]
Best for merging simple arrays.
Does not modify the original arrays.
2⃣ Using .concat()
- The
.concat()
method merges two or more arrays without modifying the originals.
Example:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = arr1.concat(arr2);
console.log(newArr); // [1, 2, 3, 4, 5, 6]
Works like the spread operator
(...)
, but slightly older.
3⃣ Using .push(...arr2)
(If You Want to Modify the Original Array)
(Not Always Recommended)
- You can use
.push()
with spread syntax (...
) to add elements of another array to an existing one.
Example:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
arr1.push(...arr2);
console.log(arr1); // [1, 2, 3, 4, 5, 6] (Modified arr1)
This modifies
arr1
, which may not always be desired.
What Happens If Arrays Contain Objects?
- If two arrays contain objects, a shallow copy is created.
- This means objects are still referenced, not duplicated.
Example:
let arr1 = [{ name: "Alice" }];
let arr2 = [{ name: "Bob" }];
let newArr = [...arr1, ...arr2];
newArr[0].name = "Eve";
console.log(arr1[0].name); // "Eve" (Changed because objects are referenced)
console.log(newArr[0].name); // "Eve"
To create a true deep copy, use
structuredClone()
or JSON.parse(JSON.stringify())
.
Quick Summary
Method | Modifies Original? | Best Use Case |
---|---|---|
...spread |
![]() |
Simple array merging |
.concat() |
![]() |
Merging multiple arrays (older method) |
.push(...arr2) |
![]() |
Adding elements to an existing array |
JSON.parse(JSON.stringify(...)) |
![]() |
Deep copy when arrays contain objects |
14. How do you remove duplicate values from an array in JavaScript? What is the most efficient way?
1. Using Set()
(Most Efficient & Recommended)
A Set
automatically removes duplicate values because it only stores unique values.
let arr = [1, 2, 3, 4, 3, 2, 1, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
Fastest & simplest way to remove duplicates.
Works with primitive values (numbers, strings, booleans).
2. Using .filter()
+ indexOf()
(Alternative for Older Browsers)
The .filter()
method checks if the current index is the first occurrence of the value.
let arr = [1, 2, 3, 4, 3, 2, 1, 5];
let uniqueArr = arr.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
Works without
Set()
, but slower for large arrays.
3. Using .reduce()
(For More Control)
You can use .reduce()
to manually build a new array without duplicates.
let arr = [1, 2, 3, 4, 3, 2, 1, 5];
let uniqueArr = arr.reduce((acc, value) => {
if (!acc.includes(value)) acc.push(value);
return acc;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
Gives more control but not as fast as
Set()
.
4. Removing Duplicates from an Array of Objects
If the array contains objects, you need to check a property to remove duplicates.
let people = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 1, name: "Alice" }
];
let uniquePeople = [...new Map(people.map(person => [person.id, person])).values()];
console.log(uniquePeople);
// [
// { id: 1, name: "Alice" },
// { id: 2, name: "Bob" }
// ]
Best way to remove duplicate objects based on a property
(id)
.
Best Choice?
Method | Works on Primitives? | Works on Objects? | Performance |
---|---|---|---|
Set() |
![]() |
![]() |
![]() |
.filter(indexOf()) |
![]() |
![]() |
![]() |
.reduce() |
![]() |
![]() |
![]() |
Map() |
![]() |
![]() |
![]() |
15. What is the difference between .find()
and .filter()
in JavaScript? When should you use each one?
.find()
vs. .filter()
Method | Returns | Stops After Finding? | Use Case |
---|---|---|---|
.find() |
First matching element | ![]() |
When you need only one result |
.filter() |
All matching elements (new array) | ![]() |
When you need multiple results |
1⃣ .find()
→ Returns First Match
.find()
stops searching as soon as it finds the first match.
Returns a single element (or undefined
if nothing is found).
let numbers = [10, 20, 30, 40, 50];
let found = numbers.find(num => num > 25);
console.log(found); // 30 (First match only)
Use
.find()
when you need only one element.
2⃣ .filter()
→ Returns All Matches
.filter()
checks every element and returns a new array with all matches.
If no elements match, it returns []
(empty array).
let numbers = [10, 20, 30, 40, 50];
let filtered = numbers.filter(num => num > 25);
console.log(filtered); // [30, 40, 50] (All matches)
Use
.filter()
when you need multiple results.
3⃣ .find()
and .filter()
with Objects
Let’s say we have an array of objects:
let users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
{ id: 4, name: "Alice" }
];
// Using `.find()` (first Alice only)
let user = users.find(user => user.name === "Alice");
console.log(user); // { id: 1, name: "Alice" }
// Using `.filter()` (all Alices)
let filteredUsers = users.filter(user => user.name === "Alice");
console.log(filteredUsers);
// [
// { id: 1, name: "Alice" },
// { id: 4, name: "Alice" }
// ]
Use
.find()
if you only need the first match.
Use
.filter()
if you need all matches.
Quick Summary
Method | Returns | Stops Early? | Works on Arrays? | Works on Objects? |
---|---|---|---|---|
.find() |
First matching element | ![]() |
![]() |
![]() |
.filter() |
New array with all matches | ![]() |
![]() |
![]() |
16. What is the difference between .some()
and .every()
in JavaScript? When should you use each one?
.some()
vs. .every()
Method | Returns | Stops Early? | Condition |
---|---|---|---|
.some() |
true if at least one element passes the test |
![]() true ) |
Checks if at least one element matches |
.every() |
true if all elements pass the test |
![]() false ) |
Checks if all elements match |
1⃣ .some()
→ Returns true
If at Least One Matches
Stops early if it finds one match.
If at least one element satisfies the condition, it returns true
.
let numbers = [3, 7, 10, 15];
// Check if there is any even number
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true (10 is even)
Use
.some()
when you need to check if at least one value matches.
2⃣ .every()
→ Returns true
Only If All Match
Stops early if it finds one non-matching element.
If all elements satisfy the condition, it returns true
.
let numbers = [2, 4, 6, 8];
// Check if all numbers are even
let allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true (All numbers are even)
Use
.every()
when all values must meet a condition.
3⃣ .some()
vs. .every()
with Objects
Let’s check an array of objects:
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 15 }
];
// Check if at least one user is under 18
let hasMinor = users.some(user => user.age < 18);
console.log(hasMinor); // true (Charlie is under 18)
// Check if all users are adults
let allAdults = users.every(user => user.age >= 18);
console.log(allAdults); // false (Charlie is under 18)
Use
.some()
to check if at least one condition is met.
Use
.every()
to ensure that all values match a condition.
Best Use Cases
Method | Use When You Need to… |
---|---|
.some() |
Check if at least one element passes the test |
.every() |
Check if all elements pass the test |
17. What is the difference between .slice()
and .splice()
in JavaScript? When should you use each one?
.slice()
vs. .splice()
in JavaScript
Method | Modifies Original Array? | Returns | Use Case |
---|---|---|---|
.slice(start, end) |
![]() |
A new array (shallow copy) | Extracts part of an array without modifying the original |
.splice(start, deleteCount, items...) |
![]() |
Removed elements (or an empty array) | Removes or replaces elements in the original array |
1⃣ .slice()
→ Extracts a Portion Without Changing Original
- Returns a new array with selected elements.
- Does not modify the original array.
let arr = [1, 2, 3, 4, 5];
let slicedArr = arr.slice(1, 4); // Extracts from index 1 to 3 (4 is not included)
console.log(slicedArr); // [2, 3, 4]
console.log(arr); // [1, 2, 3, 4, 5] (Original remains unchanged)
Use
.slice()
when you need a copy of part of an array.
2⃣ .splice()
→ Modifies the Original Array
- Can remove, replace, or insert elements.
- Modifies the original array.
let arr = [1, 2, 3, 4, 5];
// Remove 2 elements starting from index 1
let removed = arr.splice(1, 2);
console.log(removed); // [2, 3] (Removed elements)
console.log(arr); // [1, 4, 5] (Original array is modified)
Use
.splice()
when modifying the array is necessary.
3⃣ .splice()
for Inserting Elements
You can also use .splice()
to insert new elements:
let arr = [1, 2, 5];
// Insert at index 2
arr.splice(2, 0, 3, 4);
console.log(arr); // [1, 2, 3, 4, 5]
Use
.splice()
when you need to insert elements at a specific index.
4⃣ .splice()
for Replacing Elements
Replace elements by removing and adding at the same time:
let arr = [1, 2, 3, 4, 5];
// Replace 2 elements at index 1
arr.splice(1, 2, 10, 20);
console.log(arr); // [1, 10, 20, 4, 5]
Use
.splice()
for replacing elements dynamically.
Quick Summary
Method | Changes Original? | Returns | Best Use Case |
---|---|---|---|
.slice(start, end) |
![]() |
A new array | Copying part of an array |
.splice(start, deleteCount, items...) |
![]() |
Removed elements | Removing, inserting, or replacing elements |
Bonus
let arr = [1, 2, 5];
// Insert at index 2
arr.splice(2, 0, 3, 4);
console.log(arr); // [1, 2, 3, 4, 5]
What does 0
do?
The second argument in .splice(start, deleteCount, items...)
is deleteCount
, which tells JavaScript how many elements to remove from the array.
-
2
→ Start inserting at index2
-
0
→ Don’t delete anything -
3, 4
→ Insert these values at index2
How it works step-by-step:
- It goes to index 2 (before
5
). - It does not remove any elements (
deleteCount = 0
). - It inserts
3
and4
at index2
, shifting existing elements.
Before & After:
Index | Original | After splice(2, 0, 3, 4)
|
---|---|---|
0 | 1 | 1 |
1 | 2 | 2 |
2 | 5 | 3 |
3 | – | 4 |
4 | – | 5 |
Now the array is: [1, 2, 3, 4, 5]
Setting
deleteCount
to 0
ensures that no elements are removed—only new elements are inserted.
If you don’t pass 0
in .splice(start, deleteCount, items...)
JavaScript assumes the second argument as deleteCount
and removes that many elements from the array before inserting new values.
Example 1: Without 0
(Deletes Elements)
let arr = [1, 2, 5];
// Using `splice(2, 1, 3, 4)` instead of `splice(2, 0, 3, 4)`
arr.splice(2, 1, 3, 4);
console.log(arr); // [1, 2, 3, 4]
What happened here?
-
2
→ Start at index2
(where5
is). -
1
→ Delete1
element (5
is removed). -
3, 4
→ Insert these values at index2
.
Before & After:
Index | Original | After splice(2, 1, 3, 4)
|
---|---|---|
0 | 1 | 1 |
1 | 2 | 2 |
2 | 5 | 3 |
3 | – | 4 |
Since
deleteCount = 1
, 5
was removed before inserting 3
and 4
.
Example 2: Using Default deleteCount
(Deletes Everything After start
)
If you don’t pass deleteCount
at all, all elements after the start
index will be removed!
let arr = [1, 2, 5, 6, 7];
arr.splice(2); // Removes everything from index 2 onward
console.log(arr); // [1, 2]
What happened?
-
2
→ Start at index2
(where5
is). -
No
deleteCount
→ Deletes everything from index2
onward.
If
deleteCount
is missing, .splice()
removes all elements from start
to the end of the array.
Summary
Code | Effect |
---|---|
arr.splice(2, 0, 3, 4); |
Insert 3, 4 at index 2 without deleting anything. |
arr.splice(2, 1, 3, 4); |
Replace 1 element (at index 2 ) with 3, 4 . |
arr.splice(2); |
Delete everything from index 2 onward. |
18. What is the difference between .sort()
and .reverse()
in JavaScript? When should you use each one?
.sort() vs. .reverse() in JavaScript
Method | Modifies Original Array? | What It Does |
---|---|---|
.sort() |
![]() |
Sorts the array in-place (default: converts values to strings and sorts alphabetically) |
.reverse() |
![]() |
Reverses the order of the array in-place |
1⃣ .sort()
→ Sorts an Array
- Modifies the original array by default.
- Converts elements to strings and sorts them alphabetically (which can be problematic for numbers). #### Example:
let arr = [5, 20, 1, 10];
arr.sort();
console.log(arr); // [1, 10, 20, 5] (Incorrect for numbers!)
What happened?
- Since
.sort()
converts elements to strings,"10"
comes before"5"
(because"1"
comes before"5"
in string comparison).
For correct numerical sorting, pass a custom compare function:
arr.sort((a, b) => a - b);
console.log(arr); // [1, 5, 10, 20] ✅ (Correct order)
2⃣ .reverse()
→ Reverses the Array
Simply flips the order of the array.
Does not sort—just reverses the current order.
let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // [5, 4, 3, 2, 1]
Use
.reverse()
when you just need to flip the order, not sort it.
3⃣ Using .sort()
with .reverse()
If you need to sort in descending order, you can use both:
let arr = [5, 20, 1, 10];
// Correct numeric sorting + reverse
arr.sort((a, b) => a - b).reverse();
console.log(arr); // [20, 10, 5, 1]
Sort first, then reverse for descending order.
Quick Summary
Method | Changes Original? | Purpose |
---|---|---|
.sort() |
![]() |
Sorts the array (default: alphabetically, but can be customized). |
.reverse() |
![]() |
Flips the order of the array. |
19. What is the difference between forEach()
, map()
, and filter()
in JavaScript? When should you use each one?
.forEach()
, .map()
, and .filter()
in JavaScript
Method | Modifies Original Array? | Returns a New Array? | Purpose |
---|---|---|---|
.forEach() |
![]() |
![]() |
Loops through an array, but does not return a new array. |
.map() |
![]() |
![]() |
Transforms each element and returns a new array. |
.filter() |
![]() |
![]() |
Filters elements that meet a condition and returns a new array. |
1⃣ .forEach()
→ Loops Through the Array
Used for performing an action on each element.
Does not return a new array.
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
console.log(num * 2); // Prints 2, 4, 6, 8, 10
});
console.log(numbers); // [1, 2, 3, 4, 5] (Original array remains unchanged)
Use
.forEach()
when you just need to iterate through an array without modifying it.
2⃣ .map()
→ Transforms the Array
Returns a new array with modified values.
Does not modify the original array.
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (Original remains unchanged)
Use
.map()
when you need to modify elements and return a new array.
3⃣ .filter()
→ Returns a Subset of the Array
Returns a new array containing only elements that meet a condition.
Does not modify the original array.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
console.log(numbers); // [1, 2, 3, 4, 5] (Original remains unchanged)
Use
.filter()
when you want to remove elements that don’t meet a condition.
Quick Summary
Method | Use When… |
---|---|
.forEach() |
You just want to loop through an array without returning anything. |
.map() |
You need to modify each element and return a new array. |
.filter() |
You need to remove elements that don’t meet a condition and return a new array. |
20. What is the difference between flat()
and flatMap()
in JavaScript? When should you use each one?
.flat()
vs. .flatMap()
in JavaScript
Method | Modifies Original Array? | Returns a New Array? | Purpose |
---|---|---|---|
.flat() |
![]() |
![]() |
Flattens nested arrays into a single array up to a specified depth. |
.flatMap() |
![]() |
![]() |
First maps each element, then flattens the result by one level. |
1⃣ .flat()
→ Flattens Nested Arrays
Flattens an array containing nested arrays into a single array.
- Does not modify the original array, but returns a new one.
- You can specify how deep to flatten.
let arr = [1, 2, [3, 4], [5, [6, 7]]];
console.log(arr.flat());
// Output: [1, 2, 3, 4, 5, [6, 7]] (Flattens only 1 level)
console.log(arr.flat(2));
// Output: [1, 2, 3, 4, 5, 6, 7] (Flattens 2 levels)
Use
.flat(depth)
when you need to remove nested arrays.
Default depth is
1
, but you can pass a number (e.g., .flat(2)
) to control how deep to flatten.
2⃣ .flatMap()
→ Maps + Flattens
- Combines
.map()
and.flat(1)
into a single method. - Maps each element, then flattens the result only one level.
- More efficient than using
.map()
and then.flat(1)
separately.
let arr = [1, 2, 3];
let result = arr.flatMap(num => [num, num * 2]);
console.log(result);
// Output: [1, 2, 2, 4, 3, 6] (Each number is mapped to `[num, num * 2]`, then flattened)
Use
.flatMap()
when mapping elements to arrays and you want them automatically flattened.
Quick Summary
Method | Use When… |
---|---|
.flat() |
You need to remove nested arrays. |
.flatMap() |
You need to map elements and flatten the result by 1 level. |
21. What is the difference between Array.of()
and Array.from()
in JavaScript? When should you use each one?
Array.of()
vs. Array.from()
in JavaScript
Method | Purpose | Example |
---|---|---|
Array.of() |
Creates a new array from individual values. |
Array.of(1, 2, 3) → [1, 2, 3]
|
Array.from() |
Creates a new array from an iterable (e.g., array-like objects, NodeLists, Strings, Sets). |
Array.from("hello") → ["h", "e", "l", "l", "o"]
|
1⃣ Array.of()
→ Creates an Array from Values
- Takes individual values as arguments and puts them into an array.
- Useful for ensuring an array is created correctly when passing numbers.
let arr1 = Array.of(1, 2, 3);
console.log(arr1);
// Output: [1, 2, 3]
let arr2 = Array.of(5);
console.log(arr2);
// Output: [5]
Use
Array.of()
when creating an array from separate values.
Avoids confusion with the
Array()
constructor, which behaves differently.
let arr3 = Array(5);
console.log(arr3);
// Output: [empty × 5] (Creates an empty array with length 5!)
let arr4 = Array.of(5);
console.log(arr4);
// Output: [5] ✅ (Correct way to create an array with a single number)
2⃣ Array.from()
→ Creates an Array from an Iterable
- Converts iterable objects (e.g., Strings, NodeLists, Sets, Maps) into arrays.
- Can apply a mapping function while creating the array.
// Example 1: Convert a String into an Array
let str = "hello";
let arr = Array.from(str);
console.log(arr);
// Output: ["h", "e", "l", "l", "o"]
// Example 2: Convert a Set into an Array
let mySet = new Set([10, 20, 30]);
let arr2 = Array.from(mySet);
console.log(arr2);
// Output: [10, 20, 30]
// Example 3: Using a mapping function
let arr3 = Array.from([1, 2, 3], num => num * 2);
console.log(arr3);
// Output: [2, 4, 6]
Use
Array.from()
when converting iterable objects or applying transformations.
Quick Summary
Method | Use When… |
---|---|
Array.of() |
You want to create an array from individual values. |
Array.from() |
You want to convert an iterable (like a String, Set, or NodeList) into an array or apply a mapping function. |
22. How does the fill()
method work in JavaScript? What are some practical use cases?
.fill()
Method in JavaScript
The .fill()
method fills all or part of an array with a specified value.
Syntax:
array.fill(value, start, end)
-
value
→ The value to fill the array with. -
start
(optional) → The index to start filling (default is0
). -
end
(optional) → The index to stop filling (not included in the fill, default isarray.length
).
1⃣ Example: Fill an Entire Array
let arr = new Array(5).fill(0);
console.log(arr);
// Output: [0, 0, 0, 0, 0]
Useful for initializing an array with default values.
2⃣ Example: Fill a Portion of an Array
let arr = [1, 2, 3, 4, 5];
arr.fill(9, 1, 4); // Fill index 1 to 3 (not including 4)
console.log(arr);
// Output: [1, 9, 9, 9, 5]
Used to replace part of an array with a specific value.
3⃣ Example: Reset an Array
let arr = [10, 20, 30, 40, 50];
arr.fill(0);
console.log(arr);
// Output: [0, 0, 0, 0, 0]
When to Use .fill()
?
Use Case | Example |
---|---|
Initialize an array with default values | new Array(5).fill(0) |
Replace part of an array | [1,2,3,4,5].fill(9, 1, 4) |
Reset an array | [10, 20, 30].fill(0) |
23. What does the copyWithin() method do in JavaScript? How is it different from splice()?
.copyWithin()
Method in JavaScript
The .copyWithin()
method copies a portion of an array to another position within the same array, without changing its length.
Syntax:
array.copyWithin(target, start, end)
-
target
→ The index where the copied values will be placed. -
start
→ The index where copying starts (default:0
). -
end
(optional) → The index where copying stops (not included, default:array.length
). Modifies the original array (does not create a new one). ### 1⃣ Example: Copy Within the Array
let arr = [10, 20, 30, 40, 50];
arr.copyWithin(1, 3);
console.log(arr);
// Output: [10, 40, 50, 40, 50]
Explanation:
-
Target index =
1
→ Copy starts replacing from index1
. -
Start index =
3
→ Copying starts from index3
(40
). -
No end index given → Copies till the end of the array.
### 2⃣ Example: Using
end
Parameter
let arr = [1, 2, 3, 4, 5, 6];
arr.copyWithin(2, 0, 3);
console.log(arr);
// Output: [1, 2, 1, 2, 3, 6]
Explanation:
-
Target index =
2
→ Copy starts replacing from index2
. -
Start index =
0
→ Copying starts from index0
. -
End index =
3
→ Stops copying before index3
. ####.copyWithin()
vs..splice()
Method | Modifies Original Array? | Adds/Removes Elements? | Copies Elements? |
---|---|---|---|
.copyWithin() |
![]() |
![]() |
![]() |
.splice() |
![]() |
![]() |
![]() |
Key Difference:
-
.copyWithin()
only copies existing elements in the array to a new position. -
.splice()
adds/removes elements and changes the array length. ###When to Use
.copyWithin()
?
Use Case | Example |
---|---|
Quickly overwrite part of an array |
[1,2,3,4,5].copyWithin(2, 0, 2) → [1,2,1,2,5]
|
Shuffle elements within an array | arr.copyWithin(0, arr.length - 2) |
24. What is the entries()
method in JavaScript, and how does it differ from keys()
and values()
?
.entries()
, .keys()
, and .values()
Methods
These methods return iterators that allow you to loop over an array’s entries, keys, or values.
1⃣ .entries()
→ Returns Key-Value Pairs
- Returns an iterator of
[index, value]
pairs. - Useful when you need both index and value.
let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
for (let [index, value] of iterator) {
console.log(index, value);
}
// Output:
// 0 'a'
// 1 'b'
// 2 'c'
Use
.entries()
when you need both index and value while looping.
2⃣ .keys()
→ Returns Indexes
- Returns an iterator of the array’s indexes (keys).
let arr = ['x', 'y', 'z'];
let iterator = arr.keys();
for (let key of iterator) {
console.log(key);
}
// Output:
// 0
// 1
// 2
Use
.keys()
when you only need the indexes.
3⃣ .values()
→ Returns Values
- Returns an iterator of the array’s values.
let arr = [10, 20, 30];
let iterator = arr.values();
for (let value of iterator) {
console.log(value);
}
// Output:
// 10
// 20
// 30
Use
.values()
when you only need the values.
Quick Comparison
Method | Returns | Example Output |
---|---|---|
.entries() |
[index, value] pairs |
[[0, 'a'], [1, 'b'], [2, 'c']] |
.keys() |
Indexes (keys) | [0, 1, 2] |
.values() |
Values | ['a', 'b', 'c'] |
When to Use These Methods?
Use Case | Best Method |
---|---|
Need both index and value? | .entries() |
Only need indexes? | .keys() |
Only need values? | .values() |
25. What is the difference between Array.isArray()
and instanceof Array
? When should you use each?
Array.isArray()
vs. instanceof Array
Both methods check whether a value is an array, but they work differently in certain cases.
1⃣ Array.isArray(value)
→ The Reliable Way
- Returns
true
if the value is an array, even if created in a different execution context (e.g., different frames in a browser). - Best for checking if a value is an array in all cases.
console.log(Array.isArray([1, 2, 3])); // true ✅
console.log(Array.isArray({ a: 1 })); // false ❌
console.log(Array.isArray("hello")); // false ❌
Use
Array.isArray()
whenever you need a reliable way to check if a variable is an array.
2⃣ value instanceof Array
→ Context-Sensitive
- Checks if
value
was created using JavaScript’s built-inArray
constructor. -
Fails if arrays come from a different execution context (e.g.,
iframe
orwindow
).
console.log([1, 2, 3] instanceof Array); // true ✅
console.log({ a: 1 } instanceof Array); // false ❌
console.log("hello" instanceof Array); // false ❌
Use
instanceof Array
if you’re working within a single JavaScript execution context.
Avoid it if dealing with cross-frame JavaScript execution (e.g., different browser tabs or iframes).
Key Differences
Feature | Array.isArray() |
instanceof Array |
---|---|---|
Works across different JavaScript contexts (e.g., iframes)? | ![]() |
![]() |
Recommended for checking arrays? | ![]() |
![]() |
Works on built-in arrays? | ![]() |
![]() |
Works on arrays created in another window/iframe? | ![]() |
![]() |
3⃣ When to Use Each?
Scenario | Best Method |
---|---|
Checking if a value is an array (recommended way) |
Array.isArray() ![]() |
Checking array in the same execution context (basic check) |
instanceof Array ![]() |
Working with data across iframes or different windows? |
Array.isArray() ![]() |
Bonus: What are typed arrays
in JavaScript? How are they different from regular arrays?
What Are Typed Arrays in JavaScript?
Typed Arrays allow handling binary data efficiently in JavaScript.
Unlike regular arrays, they store raw binary data in a fixed format and size.
Why Use Typed Arrays?
Faster performance compared to regular arrays.
Fixed size (cannot dynamically grow/shrink).
Efficient memory usage (stores raw binary data).
Useful for handling files, WebGL, and binary protocols (e.g., images, videos).
Typed Arrays vs. Regular Arrays
Feature | Regular Array | Typed Array |
---|---|---|
Data Type | Any type (mixed values) | Only one specific type |
Size | Dynamic (can grow/shrink) | Fixed size |
Memory Efficiency | Less efficient (more overhead) | More efficient (stores raw binary data) |
Use Case | General-purpose data storage | Performance-critical tasks (binary data, WebGL) |
Creating a Typed Array
Example 1: Creating an Int16Array
let arr = new Int16Array([10, 20, 30]);
console.log(arr);
// Output: Int16Array(3) [10, 20, 30]
Stores only 16-bit integers.
Common Typed Array Types
Typed Array | Size per Element | Value Range |
---|---|---|
Int8Array |
8-bit (1 byte) | -128 to 127 |
Uint8Array |
8-bit (1 byte) | 0 to 255 |
Int16Array |
16-bit (2 bytes) | -32,768 to 32,767 |
Uint16Array |
16-bit (2 bytes) | 0 to 65,535 |
Int32Array |
32-bit (4 bytes) | -2,147,483,648 to 2,147,483,647 |
Float32Array |
32-bit floating-point | Decimal numbers |
Use the right type depending on your data range needs.
Example 2: Modifying Typed Arrays
let numbers = new Uint8Array(3); // Creates an array with 3 elements (default: 0)
numbers[0] = 5;
numbers[1] = 10;
numbers[2] = 255; // Max value for Uint8Array
console.log(numbers);
// Output: Uint8Array(3) [5, 10, 255]
Fixed size & values must be within the allowed range.
When to Use Typed Arrays?
Use Case | Use Typed Arrays? |
---|---|
General-purpose JavaScript arrays? | ![]() |
Handling binary data (files, WebGL, etc.)? | ![]() |
Performance-critical tasks (e.g., games, image processing)? | ![]() |
Congratulations on Completing This Deep Dive into JavaScript Arrays!
Arrays are one of the most powerful data structures in JavaScript, and mastering them can significantly improve your ability to write efficient and optimized code.
By understanding key methods like .map()
, .filter()
, and .reduce()
, as well as advanced concepts like typed arrays
, you’re well on your way to becoming a JavaScript pro.
If you found this guide helpful, feel free to share it with fellow developers!
Have any questions or additional insights? Drop a comment below—I’d love to hear your thoughts.
Happy coding!
This content originally appeared on DEV Community and was authored by Keshav Kumar