Back to Blog

Arrays in javascript

Ankit Kumar Jha

Author

May 27, 2025
4 min read

Core Concepts

  • Structure: Contiguous memory, index-based access, Dynamic in Python/JavaScript (flexible size), fixed in others (e.g., Java).

    • Contiguous memory means Elements stored next to each other.

  • Syntax: Three components - array name, elements, and data type.

  • Common operations:

    • Access: O(1)

    • Search: O(n) (unsorted), O(log n) (sorted)

    • Insert/Delete: O(n) (middle), O(1) (end)

  • Key Terms:

    • Subarray: Contiguous elements (e.g., [7,6,8] from [2,7,6,8,5,4]).

    • Subsequence: Non-contiguous, order preserved (e.g., [7,8,5] from the same array).

An index is always less than the total number of array items.


Array Creation

// Literal (recommended)
const arr1 = [1, 2, 3];

// Constructor (rarely used)
const arr2 = new Array(1, 2, 3);

// Static methods
const emptyArr = Array(3); // [empty × 3]
const fromStr = Array.from("hello"); // ['h','e','l','l','o']

Multidimensional Arrays

Creation & Access

// 2D Array (Matrix)
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[1][2]);       // 6 (row 1, column 2)

Real-World Use Cases

  • Game boards (Chess, Tic-Tac-Toe)

  • Image processing (pixel matrices)

  • Spreadsheet data


Basic Operations

Access/Modify Elements

const fruits = ['apple', 'banana', 'orange'];

console.log(fruits[0]); // 'apple'

fruits[1] = 'kiwi'; // Modifies array

console.log(fruits.length); // 3

2D Arrays

Operation     |  Example                      |  Description 
Access         matrix[i][j]                    Get element at row i,  column j 
Update         matrix[0][1] = 10                                Modify element 
Iteration      matrix.forEach(row =>row.forEach(cell=>...))     Nested loops

Check if Array

Array.isArray(fruits); // true

Common Methods

Add/Remove Elements

Method       |    Example                           |  Result

 push()       fruits.push('mango')         Adds to end → returns new length
 pop()        fruits.pop()                 Removes from end → returns item 
unshift()     fruits.unshift('grape')      Adds to start → returns new length 
shift()       fruits.shift()               Removes from start → returns item 
splice()      fruits.splice(1, 0, '🍊')   Inserts/removes at index
splice manupulate the array, it takes out the portion whice was given.

Iteration

Method         | Example                            | Use Case 
forEach()      fruits.forEach(f =>console.log(f))   Iterate over elements 
map()          fruits.map(f => f.toUpperCase())     Transform elements 
filter()       fruits.filter(f => f.length > 5)     Select elements 
reduce()       [1,2,3].reduce((a,b) => a + b, 0)    Accumulate values (sum: 6)

Searching

Method          | Example                          |  Result 
indexOf()       fruits.indexOf('banana')             Returns index (1) or -1 
includes()      fruits.includes('apple')             true/false 
find()          fruits.find(f => f.startsWith('a'))  Returns first match some()          fruits.some(f => f === 'kiwi')       true if any match 
every()         fruits.every(f => f.length > 3)      true if all match

Transformation

Method          | Example                         |  Result 
slice()         fruits.slice(1,3)               New array: ['banana','orange'] 
concat()        fruits.concat(['🍇','🍍'])     Merges arrays 
join()          fruits.join(', ')              "apple, banana, orange" 
reverse()       fruits.reverse()               Modifies array in-place 
sort()          [3,1,2].sort((a,b) => a - b)   Sorted: [1,2,3]
slice just take out the number execept the last one.

ES6+ Features

Spread Operator

const newFruits = [...fruits, '🍓']; // Copies and adds

Destructuring

const [first, second] = fruits; // first='apple', second='banana'

Array Methods

Method          |  Example                            |  Result 
flat()          [[1], [2,3]].flat()                    [1,2,3] 
flatMap()       [1,2].flatMap(n => [n, n*2])           [1,2,2,4] 
fill()          Array(3).fill(0)                       [0,0,0]

Combining Arrays

const marvel = ["thor", "ironman", "spiderman"];
const dc = ["superman", "flash", "batman"];

// ❌ Bad (nested array)
marvel.push(dc); // ["thor", "ironman", "spiderman", ["superman", "flash", "batman"]]

// ✅ Good (concat), problem: here you can only give one values in concat.
const allHeros = marvel.concat(dc); // ["thor", "ironman", "spiderman", "superman", "flash", "batman"]

// ✅ Best (spread)
const allNewHeros = [...marvel, ...dc]; // Same as concat but more flexible

Flattening Arrays

const nested = [1, 2, [3, 4, [5, 6]]];

// Flatten 1 level
const flat1 = nested.flat(1); // [1, 2, 3, 4, [5, 6]]

// Flatten all levels
const flatAll = nested.flat(Infinity); // [1, 2, 3, 4, 5, 6]
 flat => returns  new array with all sub array elements concatenated into it         
         recursively up to the specified depth.

Converting to Array

console.log(Array.isArray("Ankit"));     // false
console.log(Array.from("Ankit"));        // ['A','n','k','i','t']
console.log(Array.from({name: "Ankit"})); // [] (requires keys/values)

Creating Arrays from Variables

let score1 = 10, score2 = 20, score3 = 30;
console.log(Array.of(score1, score2, score3));       // [10, 20, 30]
 of => returns a new array from set of elements

Common Use Cases

Remove Duplicates

const unique = [...new Set([1,2,2,3])]; // [1,2,3]

Shuffle Array

const shuffled = [...fruits].sort(() => Math.random() - 0.5);

Empty an Array

fruits.length = 0; // Clears the array

Common Pitfalls

  • slice vs splice:

    • slice: Copies (non-destructive).

    • splice: Modifies (destructive).

  • Shallow Copies:

const arr = [{a:1}];
const copy = [...arr]; // Objects are referenced, not cloned.
  • Sparse Arrays:

const sparse = [1,,3]; // Index 1 is empty.

Summary

Task               Method/Pattern
Add to end         push()
Remove from end    pop()
Clone array        [...arr] or slice()
Check existence    includes()
Transform elements  map()
Flatten arrays      flat()/flatMap()
Empty array         arr.length = 0

Share your thoughts on Arrays in the comments below!

Let's connect and learn from each other!
Thanks for reading this article.


Subscribe to my Newsletter
Get the latest articles, tutorials, and updates delivered straight to your inbox. No spam, unsubscribe anytime.

By subscribing, you agree to receive emails from this blog. You can unsubscribe at any time.