Photo by Pankaj Patel on Unsplash

All about arrays in Javascript

Pratik Rai
2 min readMar 4, 2025

An array in javascript is a type of object(kind of single object with multiple values) , which allows us to store items of multiple types (number, string, etc) under a single variable name. It provides a number of operations that we can perform to do a variety of things.

// syntax
let array = ["apple" , 1 , "orange"];
let array2 = new Array(1,2,3,4,5)
let array3 = new Array(5); // array of size 5 with uninitialized values
let array4 = new Array(5).fill(0) // array of size 5 with all values 0
let array5 = new Array.from("Hello"); // ['h','e','l','l','o']

Operations on arrays :

// push operation
array.push("Hello");

// pop -> remove from the end
array.pop()

// unshift -> add to beginning
array.unshift(2); // [ 2, "apple" , 1 , "orange"];

// shift -> remove from beginning
array.shift()

// find -> gives the first matching element
let evenNumber = array.find(function(number){
return number > 1
} // gives 2

// the above can also be re written with arrow operator
let evenNumber = array.find((number) => number > 1);

// includes -> check if the value exists
array.includes(2)

// sort and reverse
array.sort()
array.reverse()

// join array
let newArray = array.join("#") // joins array elemens with # in between

//slice array -> returns a new array fromIndex to toIndex without
//modifying the original

let slicedArray = array.slice(1,2); // slice(fromIndex, toIndex)

// splice -> removes and adds elements in the original array
array.splice(1,1,10) // removes 1 element from index 1 and adds 99

// some and every
// some -> Check if at least one element satisfies a condition
let hasEven = arr.some(num => num % 2 === 0); // true

// every -> Check if all elements satisfy a condition
let hasAllEven arr.every(num => num % 2 === 0)

There are more important array operations like map filter and reduce , but I will share more about them in a seprate post.

As of now these are all the array operations that you will be needing for most of the use cases.

If you like the post, do give claps.

--

--

No responses yet