JavaScript Arrays

Arrays are built-in global objects that allows you to store multiple elements at once. This page explains about what an Array is. We will also see some methods and properties to make our lives easier when we are dealing with JavaScript arrays. For example, the sort() method of an Array can be used to sort all its elements using custom or default rules.

Arrays in JavaScript

Contents

  1. Introduction to JavaScript Arrays
  2. Characteristics of JavaScript Arrays
  3. Creating JavaScript Arrays
  4. Getting/Accessing JavaScript Array Elements
  5. Modifying Array Elements
  6. Fetching Array's Size
  7. Basic Array Operations

Introduction to JavaScript Arrays

Objects are useful for storing keyed collections of values. However, we often need an ordered collection, such as a list of something: users, goods, HTML elements, etc. That’s where Arrays come in handy; they allow us to add new elements anywhere in the sequence and provide methods to manage the order or manipulate the elements.

In short, an array is an ordered list of values. Each value is called an element specified by an index.

Characteristics of JavaScript Arrays

  1. An Array is a group of related data items
  2. It can store multiple values of the same or mixed type(s)
  3. An array may be declared when it is defined. However, it cannot be initialized until after its definition
  4. All elements of an array can be distinguished with the help of an index number that identifies each element uniquely
  5. They are dynamic in nature. You can add or remove elements from an array at any time. Also, you don't need to specify the type or size upfront
  6. Array types: integer, string, boolean or floating-point (real) data types

Example of a Simple Array

var myArray = [1, 2, 3, 4, 5];

Example of a Mixed Array

var myArray = [1, 'JavaScript', false, null, { name: 'Jane' }];

Creating JavaScript Arrays

There are multiple methods of creating arrays in JavaScript. We will see four of those methods in this section below.

  1. Creating Arrays Using Array() Constructor Method
  2. Creating Arrays Using Literal Notation Method
  3. Creating Arrays Using Spread Operator
  4. Creating Arrays From Another Arrays

1. Creating Arrays Using Array() Constructor Method

The Array constructor can be used as given in the example below:

let fruits = new Array();

We have created a fruits array above that doesn't have any size or contain any values/elements yet.

In many situations, we will know the exact size of the array that we need to create. In such cases, we can create the array as shown below:

let fruits = Array(10);

To create an array and initialize it with some elements, you pass the elements as a comma-separated list into the Array() constructor.

For example, the following creates the fruits array that has three elements/fruits (of string type):

let fruits = new Array('Banana', 'Orange', 'Mango');

Note that if you use the Array() constructor to create an array and pass a number into it, you are creating an array with an initial size.

However, when you pass an element of another type like number into the Array() constructor, you create an array with an element of that value. For example:

let fruits = new Array(3); // creates an array with initial size 3
let colors = new Array('Red', 'Green', 'Yellow'); // create an array with three color strings 'Red', 'Green', 'Yellow'
let animals = new Array('Lion', 'Tiger'); // creates an array with 2 elements 'Lion' & 'Tiger'

You can also omit the new operator in JavaScript while creating arrays using the Array() constructor method.

For example, the following statement creates the sports array.

let sports = Array();

We rarely use the Array() constructor method to create an array in real situations.

2. Creating Arrays Using Literal Notation Method

A better and preferred way to create an array is using the array literal notation.

We will use the square brackets [] to wrap a comma-separated list of elements/values to create the array.

let myArray = [item1, item2, item3];

The following example creates the fruits array that has fruit names as strings.

let fruits = ['Banana', 'Orange', 'Mango'];

In cases where you don't know the array elements upfront, you can simply specify empty square brackets without adding any element to it.

let emptyArray = [];

3. Creating Arrays Using Spread Operator

This is one of the easiest ways of creating arrays. It depends on the use case you're dealing with when it comes to using this method. Sometimes, you may need to create an array that acts as a combination of two different categories.

Let's say you need to create an array that contains both fruits and vegetables where this method will be extremely useful.

const fruits = ['Banana', 'Orange', 'Mango'];
const fruitsAndVegetables = ['Potato', 'Beans' ...fruits ];

As you can see above, we have created a second array fruitsAndVegetables with a pre-existing array fruits using spread operator (...).

Learn more about spread operator...

4. Creating Arrays From Another Arrays

Here, we are going to create an array fruits. You can use either method discussed above, i.e, either using the array constructor method or the literal notation method. We will then create the second array fruitsAndVegetables using the previously created array fruits with the help of Array.from() method.

const fruits = new Array('Banana', 'Orange', 'Mango');
const fruitsAndVegetables = Array.from(fruits);

Getting/Accessing JavaScript Array Elements

As you know that JavaScript arrays are index based where the index start from 0, to access an element in an array, we need to specify an index in the square brackets [] when we need to fetch the elements of an array.

In the example below, we first write the array name and then the square brackets [] inside which we mention the index of the element we need.

myArray[2]; // returns the element at index `2`, i.e., the third element of the array

The following shows how to access the elements of the scores array:

let scores = [10, 9, 8, 7, 6];
console.log(scores[0]); // 10
console.log(scores[1]); // 9
console.log(scores[2]); // 8
console.log(scores[3]); // 7
console.log(scores[4]); // 6

Modifying Array Elements

To change an element inside the array, we need to assign the new element/value using the array name and index.

Here, we have an array fruits that has three elements Banana, Orange, and Mango. Let's say we want to discard Orange and add Papaya to the array in its place. The index of Orange in the fruits array is 1. So, we will use the array name, i.e., fruits and index 1 to change the element.

const fruits = new Array('Banana', 'Orange', 'Mango');
fruits[1] = 'Papaya';

console.log(fruits); // ['Banana', 'Papaya', 'Mango']

Fetching Array's Size

We can easily get the size of an array using the length property of JavaScript arrays.

const fruits = new Array('Banana', 'Orange', 'Mango');
console.log(fruits.length); // 3

Basic Array Operations

  1. Push/Add an element to the end of an array
  2. Pop/Remove an element from the end of an array
  3. Add an element to the beginning of an array
  4. Remove an element from the beginning of an array
  5. Find the index of an element in the array
  6. Check if a value is an array

In this section, we will see some commonly used array operations. These operations can be used in the real project and more often than not, you will need these as a reference until you remember the syntax after you have practised enough.

1. Push/Add an element to the end of an array

We will use the Array.push() to add an element to the end of an array as shown in the example below:

let fruits = ['Banana', 'Orange', 'Mango'];
fruits.push('Guava');

console.log(fruits); // ['Banana', 'Orange', 'Mango', 'Guava']

2. Pop/Remove an element from the end of an array

We will use the Array.pop() to remove an element from the end of an array as shown in the example below:

let fruits = ['Banana', 'Orange', 'Mango', 'Guava'];
const poppedElement = fruits.pop();

console.log(poppedElement); // Guava
console.log(fruits); // ['Banana', 'Orange', 'Mango']

3. Add an element to the beginning of an array

We will use the Array.unshift() to add an element to the beginning of an array as shown in the example below:

let fruits = ['Banana', 'Orange', 'Mango', 'Guava'];
fruits.unshift('Apple');

console.log(fruits); // ['Apple', 'Banana', 'Orange', 'Mango', 'Guava']

4. Remove an element from the beginning of an array

We will use the Array.shift() to remove an element from the beginning of an array as shown in the example below:

let fruits = ['Banana', 'Orange', 'Mango', 'Guava'];
const firstElement = fruits.shift();

console.log(firstElement); // Banana
console.log(fruits); // ['Orange', 'Mango', 'Guava']

5. Find the index of an element in the array

We will use the Array.indexOf() to find the index of an element in the array as shown in the example below:

let fruits = ['Banana', 'Orange', 'Mango', 'Guava'];
let elementIndex = fruits.indexOf('Orange');

console.log(elementIndex); // 1

6. Check if a value is an array

We will use the Array.indexOf() to to check if a value is an array as shown in the example below:

Array.isArray(['Banana', 'Orange', 'Mango', 'Guava']); // true
Array.isArray({ name: 'Jane' }); // false
Array.isArray('Jane'); // false
Array.isArray(undefined); // false

So far we have seem some commonly used array operations. Now that we know the array syntax pretty well, we will dive into some of the advanced operations that will make your life easier when dealing with issues in real life projects.

We will see methods such as map(), filter(), reduce(), etc.

Summary

In this tutorial, we have learnt the basics of JavaScript arrays, characteristics, syntax, and some basic array operations. We have seen that an array is a collection of values, where each value is associated with an index. An array can be of multiple data types. They can contain single or mixed values of same or different data types and they can grow or shrink as and when required.

Please checkout our related content section below for more tutorials on similar topics.


We hope that you have learnt something from our tutorials. Please feel free to share this content with your friends.


If you have any questions or want some other content to be added to our website so that it can help you learn and grow further, please do not hesitate to contact us at info@createmysite.org. We would love to hear from you.

We are hiring!! If you are tech blogger who loves writing content on modern technologies, we would love to get in touch with you. Just drop us a mail at the email address mentioned above and we will reach out to you as soon as possible.

If you are interested in learning more about our website, please visit our about page.