DEV Community

Cover image for All you need to know about arrays in JavaScript
MAYANK TYAGI
MAYANK TYAGI

Posted on • Edited on

All you need to know about arrays in JavaScript

Arrays in JavaScript

In JavaScript, arrays are used to store multiple values or you can think of an array as an ordered list of values (more specific elements).

Unlike Java or C++ in JavaScript, an array can store values of different data types and you also don't need to specify the size of array while declaring it as it can grow automatically as per requirement or you can say length of array is dynamically sized and auto-growing.

let array=[1,"Java", 2,"CPP", 3,"JS", 3.5,"HTML"];
console.log(array);

// Output [1, "Java", 2, "CPP", 3, "JS", 3.5, "HTML"]
Enter fullscreen mode Exit fullscreen mode

In JavaScript arrays are special type of objects, but let's not worry about that much and treat it as normal array for now

let array=[1, "Java", 2, "CPP", 3, "JS", 3.5, "HTML"];
console.log(typeof(arrayObj));

// Output "object"
Enter fullscreen mode Exit fullscreen mode

Ways of creating an array in JavaScript

In JavaScript, you can create arrays in two ways, one via JavaScript keyword i.e., Array Constructor and the another way is via array literals(Easiest and most preferred way)

1. Creating array via Array Constructor:

let arrayObj = new Array(1,2,3,4,"Red");
console.log(arrayObj);

// Output [1, 2, 3, 4, "Red"]
Enter fullscreen mode Exit fullscreen mode

2. The preferred way to create an array is to use the array literal notation:

let array=[1,"Java",2,"CPP",3,"JS",3.5,"HTML"];

console.log(array);

// Output [1, "Java", 2, "CPP", 3, "JS", 3.5, "HTML"]
Enter fullscreen mode Exit fullscreen mode

Accessing the array elements

In JavaScript, arrays are zero-indexed which means the first element of an array is at index 0, and the last element is at the index value of arrays length minus 1.

let array=[1,"Java",2,"CPP",3,"JS",3.5,"HTML"];

// length of array = 8

console.log(array[0]);    //Output  1
console.log(array[2]);    //Output  2
console.log(array[3]);    //Output  "CPP"
console.log(array[6]);    //Output  3.5
console.log(array[7]);    //Output  "HTML"
console.log(array[8]);    //Output  undefined 
Enter fullscreen mode Exit fullscreen mode

Length property of Array

The length property sets or returns the number of elements in an array

let cities=["Delhi", "Mumbai", "Los Angeles", "London", "New York", "Tokyo", "Mexico City"];
console.log("Length of cities Array is "+cities.length);
// Output "Length of cities Array is 7"

let countryCode=["001", "002", "003", "004", "005", "006"];
countryCode.length=3;
console.log("Length of countryCode Array is "+countryCode.length);

// Output "Length of countryCode Array is 3"

console.log("CountryCode Array after setting size to 3",countryCode)

// Output "CountryCode Array after setting size to 3",  ["001", "002", "003"]
Enter fullscreen mode Exit fullscreen mode

Let's learn some important methods of array in JavaScript

1. push()

The push() method adds new elements to the end of an array.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
cities.push("New York");
console.log(cities);

//Output ["Delhi", "Mumbai", "Los Angeles", "London", "New York"]
Enter fullscreen mode Exit fullscreen mode

2. pop()

The pop() method removes the last element of an array, and returns that element.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
console.log(cities.pop());

//Output "London"

console.log(cities);

//Output ["Delhi", "Mumbai", "Los Angeles"]
Enter fullscreen mode Exit fullscreen mode

3. concat()

The concat() method is used to join two or more arrays.
This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

let cities1=["Delhi", "Mumbai", "Los Angeles", "London"];
let cities2=["Pune", "Kolkata", "Moscow"];
let cities=cities1.concat(cities2);
console.log(cities);

//Output ["Delhi", "Mumbai", "Los Angeles", "London", "Pune", "Kolkata", "Moscow"]
Enter fullscreen mode Exit fullscreen mode

4. slice()

The slice() method takes two arguments as starting index and ending index and returns the new array object selecting the elements from starting index to ending index(excluding end index).
Syntax
slice(startIndex,endIndex)

let cities=["Delhi", "Mumbai", "Los Angeles", "London", "Pune"];
let silceCities=cities.slice(1,4);

console.log(silceCities);

//Output ["Mumbai", "Los Angeles", "London"]
Enter fullscreen mode Exit fullscreen mode

5. splice()

The splice() method adds/removes items to/from an array,
and returns the removed item(s).
Syntax
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1....)

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];

console.log(cities.splice(1,2));

//Output ["Mumbai", "Los Angeles"]

console.log(cities);

//Output ["Delhi", "London"]

cities.splice(1,0,"Mumbai", "Los Angeles", "London")
console.log(cities);

//Output ["Delhi", "Mumbai", "Los Angeles", "London", "London"]
Enter fullscreen mode Exit fullscreen mode

6. toString()

The toString() method returns a string with all the array values, separated by commas.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
console.log(cities.toString());

//Output "Delhi,Mumbai,Los Angeles,London"
Enter fullscreen mode Exit fullscreen mode

7. sort()

The sort() method sorts the items of an array.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
cities.sort();
console.log(cities);

//Output ["Delhi", "London", "Los Angeles", "Mumbai"]
Enter fullscreen mode Exit fullscreen mode

8. reverse()

The reverse() method reverses the order of the elements in an array.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
cities.reverse();
console.log(cities);

//Output ["London", "Los Angeles", "Mumbai", "Delhi"]
Enter fullscreen mode Exit fullscreen mode

9. indexOf()

The indexOf() method searches the array for the specified element, and returns its position.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let pos=cities.indexOf("London");
console.log(pos);

//Output 3
Enter fullscreen mode Exit fullscreen mode

Similar to indexOf() there is another method lastIndexOf() as the name suggest, it returns the index of last occurence of the element in an array.

10. isArray()

The isArray() method determines whether an object is an array. This returns true if the object is an array, and false if not.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let res=Array.isArray(cities);
console.log(res);

//Output true
Enter fullscreen mode Exit fullscreen mode

11. includes()

he includes() method determines whether an array contains a specified element.
Syntax
includes(searchElement)
includes(searchElement, fromIndex)

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let res1=cities.includes("Mumbai");
console.log(res1);
//Output true

let res2=cities.includes("Mumbai",2);
console.log(res2);

//Output false
Enter fullscreen mode Exit fullscreen mode

12. join()

The join() method takes single argument and convert all the array elements into a string and return the converted string.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
console.log(cities.join(" - "));

//Output "Delhi - Mumbai - Los Angeles - London"
Enter fullscreen mode Exit fullscreen mode

13. shift()

The shift() method removes the first item of an array.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
cities.shift();
console.log(cities);

//Output ["Mumbai", "Los Angeles", "London"]
Enter fullscreen mode Exit fullscreen mode

14. unshift()

The unshift() method adds new items to the beginning of an array, and returns the new length.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
cities.unshift("New York","Tokyo");
console.log(cities);

//Output ["New York", "Tokyo", "Delhi", "Mumbai", "Los Angeles", "London"]
Enter fullscreen mode Exit fullscreen mode

15. fill()

The fill() method fills the specified elements in an array with a static value. You can specify the position of where to start and end the filling. If not specified, all elements will be filled.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
cities.fill("Delhi");
console.log(cities);

//Output ["Delhi", "Delhi", "Delhi", "Delhi"]
Enter fullscreen mode Exit fullscreen mode

16. find()

The find() method returns the value of the first element in an array that pass a test (provided as a function).

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let city=(c)=>{
return c.length>=6;
}
console.log(cities.find(city));

//Output "Mumbai"
Enter fullscreen mode Exit fullscreen mode

17. findIndex()

The findIndex() method returns the index of the first element in an array that pass a test (provided as a function).

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let city=(c)=>{
return c.length>=6;
}
console.log(cities.findIndex(city));

//Output 1
Enter fullscreen mode Exit fullscreen mode

18. forEach()

The forEach() method calls a function once for each element in an array, in order.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let city=(c,idx,arr)=>{
arr[idx]= c + " is a beautiful city";
}

cities.forEach(city);
console.log(cities);

//Output ["Delhi is a beautiful city", "Mumbai is a beautiful city", "Los Angeles is a beautiful city", "London is a beautiful city"]
Enter fullscreen mode Exit fullscreen mode

19. map()

The map() method creates a new array with the results of calling a function for every array element.

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let city=cities.map((c)=>{
return c + " is a beautiful city";
})

console.log(city);

//Output ["Delhi is a beautiful city", "Mumbai is a beautiful city", "Los Angeles is a beautiful city", "London is a beautiful city"]
Enter fullscreen mode Exit fullscreen mode

20. filter()

The filter() method creates an array filled with all array elements that pass a test (provided as a function).

let cities=["Delhi", "Mumbai", "Los Angeles", "London"];
let city=(c)=>{
return c.length>6;
}
console.log(cities.filter(city));


//Output ["Los Angeles"]
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

"Don't miss out" Follow my Social handles👉
Subscribe my YouTube channel😊
Instagram😊 || Twitter😊

If you find this helpful and want to support💲 Buy Me Coffee☕

Top comments (7)

Collapse
 
rawalprashant profile image
Prashant Raval

Amazing...Thanks for sharing.

Collapse
 
meo3w profile image
Phil Hasenkamp

You did an awesome job with this! Well done!

Collapse
 
oracledecounselor profile image
Oracledecounselor

Thanks a lot for sharing

Collapse
 
nirajbadaik profile image
NirajBadaik

Thanks for sharing. Waiting for - All you need to know about Objects version.

Collapse
 
codify_js profile image
Abhishek Kumar • Edited

Gr8 explanation

Collapse
 
iamkeshavtyagi profile image
KESHAV TYAGI

Your coffee ☕ price is too expensive 😂 for me but content is really informative 👌

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

Great share!
Now, this opens the gate to learn about array mutations and its pros and cons.