JavaScript Array – How to Use Them?

JavaScript Array – How to Use Them?

8 mins read1.1K Views Comment
Chanchal
Chanchal Aggarwal
Senior Executive Content
Updated on May 14, 2024 14:25 IST

JavaScript arrays are versatile, ordered collections of elements that can hold items of any data type, including numbers, strings, or objects. They offer a range of methods for traversal, manipulation, and searching, making them essential for handling lists and datasets in web development. Arrays in JavaScript are dynamic, allowing elements to be added or removed and their size to change during runtime.

2022_11_Arrays-in-Javascript.jpg

JavaScript Arrays are global objects that store data. An array is a collection or list of zero or more data types and contains numbered indices starting with 0. Arrays are highly helpful because they allow individuals to organize and condense code, making it easier to read and maintain. They do this by storing several values in a single variable. Additionally, JavaScript arrays are capable of holding any data, including objects, characters, and integers. Let's understand this essential JavaScript concept with the help of examples.

Explore Online JavaScript Courses and learn about its essential concepts 

Table of Contents

What is JavaScript Array?

An array is a fundamental data structure used to store a collection of elements. JavaScript array is a special variable that consists of one or more values. A JavaScript Array is a dynamic, high-level, list-like object used to store ordered collections. Elements can be of any type and are accessed by their index. Arrays in JavaScript are mutable, allowing for operations like adding, removing, and altering elements using built-in methods. 

Syntax: 


 
const array_name = [“item1”, “item2”, “item3”];
Copy code

Example:


 
const colors = [“Black”, “White”, “Blue”];
Copy code

Explanation:

The above code defines a constant array named 'colors' containing three string elements: "Black", "White", and "Blue". Since the code only declares and initializes the array but doesn't include any operations or commands to display or manipulate the array, there's no output to be shown from this snippet as it stands.

If you want to see the contents of the array displayed, you would need to add a command to do so, such as console.log(colors); which would output the array to the console.

Characteristics of JavaScript Array

A Javascript array has the following characteristics:

  • JavaScript Array object allows you to store multiple values in a single variable.
  • Values of the same or different data types can be used within a JavaScript Array.
  • JavaScript arrays use only nonnegative integers as indexes
  • The first element in a JavaScript array is at index 0, the second element at index 1, and so on. (Total size: arrayLength – 1)
  • An array can contain values of mixed types. For example, you can have an array that includes elements with string types, numbers, boolean, and null.
  • An array is dynamic and can increase in size. In other words, defining the array size in advance is not necessary.

15+ JavaScript Array Methods with Examples
15+ JavaScript Array Methods with Examples
JavaScript array methods offer powerful tools for manipulating arrays. Key methods include 'push()' and 'pop()' for adding/removing elements at the end, 'shift()' and 'unshift()' for operations at the beginning, 'map()'...read more

JavaScript Array Sort
JavaScript Array Sort
The JavaScript array.sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order, but a custom...read more

Consider assigning the five colors to their own items to demonstrate how arrays can be useful.

Example:


 
// Assign the five colors to five items
let color1 = "Black";
let color2 = "White";
let color3 = "Blue";
let color4 = "Purple";
let color5 = "Red";
Copy code

Therefore, due to its verbosity, it is tough to track and maintain.

We can organize our data with the help of arrays.

Example:


 
constcolors = [
"Black",
"White",
"Blue",
"Purple",
"Red",
];
Copy code

How to Remove Duplicates from JavaScript Array?
How to Remove Duplicates from JavaScript Array?
Entering some items twice is a common problem one can face while entering data in a system. It can be duplicates of names while entering students’ names and numbers or...read more

How to Find the JavaScript Array Length
How to Find the JavaScript Array Length
The length property of a JavaScript array returns the number of elements in the array, providing an easy way to determine its size. It's dynamic, meaning it updates as elements...read more

How to Declare Javascript Array?

The array literal in JavaScript makes it easy to create an array.

Let’s find out how to declare an array using var, const, and let.

Syntax:


 
var array_name = [item1, item2,];
Copy code

Example: 


 
var colors= [“Black”, “White”, “Blue”];
Copy code

Syntax:


 
const array_name = [item1, item2, ...];
Copy code

Example:


 
const colors = [ “Black” , “White” , “Blue” ];
Copy code

We commonly declare an array with a const keyword.

NOTE: Use const when you want to keep your array fixed and constant/unchanged.


 
const colors = [ “Black” , “White” , “Blue” ];
const colors =[ “Pink” , “White” , “Green” ]; // Error
Copy code

We cannot change the element of the constant array.

Example:


 
const colors = ["Black", "White", "Blue"];
//Changing an element
colors[0] = "Pink";
//Adding an element
colors.push("Green");
Copy code

Using let


 
let array_name= [item1, item2, ...];
Copy code

Example:


 
let colors = [ “Black” , “White” , “Blue” ];
Copy code

NOTE: Let is used when the value of the JavaScript array needs to be changed. 

Example: 


 
const price1= 7;
const price2= 8;
let total= price1 + price2;
Copy code

Here, in the above example, price1 and price2 are declared using the const keyword as their values are constant and cannot be changed.

Variable total is declared with the let keyword as its value can be changed.

Want to Become a Certified JavaScript Developer? Check these Free Courses and Certifications

JavaScript Array Push
JavaScript Array Push
The JavaScript array.push() method adds one or more elements to the end of an array, directly modifying the original array. It's widely used for dynamically expanding arrays, and conveniently returns...read more

How to Use JavaScript Array Filter
How to Use JavaScript Array Filter
The JavaScript array.filter() method creates a new array filled with elements that pass a test provided by a function. It's a powerful tool for quickly extracting subsets of data from...read more

Initializing Javascript Array – Different Methods

A comma-separated set of constant expressions encased in braces () serves as an array’s initializer. You can put an equal sign (=) in front of the initializer.It is not necessary to initialize every element in an array. Hence, if an array is partially initialized, the value 0 of the proper type is assigned to any uninitialized items.

There are two ways to define and initialize an array: array literal syntax and Array constructor syntax.

  1. Array Literal

An array literal is a list of elements present within square brackets in an array. When you create an array using an array literal, its length is set to the number of arguments supplied, and its components are initialized with the specified values.

Syntax:


 
const <array-name> = [element0, element1, element2,... elementN];
Copy code

Example: Declare and initialize a JavaScript Array


 
const stringArray = ["one", "two", "three"];
const numericArray = [1, 2, 3, 4];
const decimalArray = [1.1, 1.2, 1.3];
const booleanArray = [true, false, false, true];
const mixedArray = [1, "two", "three", 4];
Copy code

NOTE: JavaScript array can include constant elements of same or different data types.

  1. Array Constructor

The JavaScript Array constructor method returns the constructor function of an array object. This method only returns the reference of the function and not the functions’ name. Hence, JavaScript arrays return the function Array() [[native code]]. Moreover, in this method, you can initialize an array with an Array constructor syntax, a new keyword.

It is possible to display array constructors in three different ways:

Syntax:


 
const arrayName = new Array();
const arrayName = new Array(Number length);
const arrayName = new Array(element1, element2, element3,... elementN);
Copy code

As shown in the above syntax, an array can be initialized using a new keyword in the same way as an object.

The following example demonstrates how to define an array using the Array constructor syntax.

Example:


 
conststringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";
const numericArray = new Array(3);
numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;
const mixedArray = new Array(1, "two", 3, "four");
Copy code

NOTE: An array can only have a numeric index (key). The index cannot be of string or any other data type. The following syntax is incorrect.

Example: Incorrect Array Index


 
const stringArray = new Array();
stringArray["one"] = "one";
stringArray["two"] = "two";
stringArray["three"] = "three";
stringArray["four"] = "four";
Copy code

Difference between Java and JavaScript | Java vs Javascript
Difference between Java and JavaScript | Java vs Javascript
Java and JavaScript are one of the two most popular programming languages that are used by developers around the globe. In this article, we will discuss the difference between two...read more

JavaScript Object Methods- How to Use Them?
JavaScript Object Methods- How to Use Them?
JavaScript methods are actions that can be executed on objects. This article will discuss JavaScript method objects, types of JavaScript methods, and their features. You will learn about its various...read more

How to Access Array Elements

Indexing an Array

Name/value pairs are not present in arrays.Their indexes begin with 0 rather than with a decimal number. As an example, we show a color array. Square brackets enclosed in JavaScript arrays denote the index numbers of items.

Example:


 
let colors = [
"black",
"white",
"blue",
"purple",
"red",
];
Copy code

In the following table you can see the index array for each element in the colors array.

Black White Blue Purple Red
0 1 2 3 4

The first item in the array is Black, which is indexed at 0. The last item is Red, which is indexed at 4. In an array, index begins at 0 and ends at (array_length – 1).

Accessing an Array

You can access array elements by specifying their index number within square brackets.

Example:


 
colors[1];
Copy code

Output:

white

Changing JavaScript Array Element

Adding an Item to JavaScript Array

In our color, we had five items, whose indices ranged from 0 to 4. So, if we want to add a new item to the array, we can assign a value to the next index.

Example:


 
colors[5] = "pink";
colors;
Copy code

Output:

[ 'black',
	'white',
	'blue',
	'purple',
	'red',
	'pink' ]

NOTE: The array will become undefined if we add an item and accidentally skip an index.

Example:


 
colors[7] = "yellow";
Copy code

Output:


 
[ 'black',
'white',
'blue',
'purple',
'red',
'pink'
,
'yellow' ]
Copy code

An attempt to access the extra array item will return undefined.

Example:


 
colors[6]
Copy code

Output:

undefined

As a result, such issues can be managed using the push() method, which includes adding an element to the end of an array.

Example:

// Append green to the end of the colors array


 
colors.push("green");
colors;
Copy code

Output:

Output
['black',
	'white',
	'blue',
	'purple',
	'red',
	'pink' 
	,
	'yellow'
        ‘green’ ]

On the other hand, the unshift() method adds an element to the beginning of an array.

Example:

// Append orange to the beginning of the colors array


 
colors.unshift("orange");
colors
Copy code

Output:

[ 'orange',
	['black',
	'white',
	'blue',
	'purple',
	'red',
	'pink' 
	,
	'yellow'
        'green’ ]

In the above examples, we have push() and unshift(), two JavaScript array methods used to append items to the start and end of an array.

Removing an Item from JavaScript Array

The splice() technique eliminates a specific item from an array. Let’s remove the previously undefined array item we unintentionally added to the colors array.

Example:


 
colors.splice(7, 1);
colors;
Copy code

Output:

[‘orange’
        'black',
	'white',
	'blue',
	'purple',
	'red',
	'pink' 
	'yellow'
             ‘green’]

Splice() will modify the original item. Use splice() and assign the result to a new item if you want the original variable to stay the same. Here, we’ll assign two items: one that uses splice() to hold the colors array up till the pink element and another that stores the yellow and green items.

Modifying Items in JavaScript Array

Example:

// Assign brown to the first item in the color array


 
colors[0] = "brown";
colors;
Copy code

Output:

[ 'brown',
	 'black',
	'white',
	'blue',
	'purple',
	'red',
	'pink' ]

Using the splice() method with a new parameter is an additional technique of changing a value. As a result, blue, the item at index 3, might be deleted and a new item added instead, if we want to alter its value.

Example:

// blue with peach using splice method


 
colors.splice(3, 1, "peach");
colors();
Copy code

Output:

[ 'brown',
	 'black',
	'white',
	'peach',
	'purple',
	'red',
	'pink' ]
    

Therefore, in the aforementioned illustration, blue was removed from the array, while index 3 was replaced with a new value.

Prepare for your next Javascript interview – Most Asked Javascript Interview Questions

Wrapping It Up!!

Arrays are fundamental, essential, and versatile part of programming in JavaScript. In the above blog, we have covered what Array is, why we use it, and how to declare and initialize an array in Javascript. Also, topics such as how to access and change an array element, i.e, creating, removing, and modifying items along with its different operations, have been explained.  

Top FAQs on JavaScript Array

What is a JavaScript Array?

A JavaScript array is an ordered collection of items, which can be of different data types like strings, numbers, or objects. Arrays are used to store multiple values in a single variable.

How do you create an Array in JavaScript?

You can create an array using square brackets []. For example, let fruits = ["apple", "banana", "mango"];.

How do you add an item to an Array?

You can add an item using the push() method for adding to the end, or unshift() for adding to the beginning. For example, fruits.push("orange");.

How do you remove an item from an Array?

Use pop() to remove the last item or shift() to remove the first item. You can also use splice() to remove items at a specific index.

How do you access an item in an Array?

Access items by their index, starting with 0. For example, fruits[0] will access the first item, "apple".

About the Author
author-image
Chanchal Aggarwal
Senior Executive Content

Chanchal is a creative and enthusiastic content creator who enjoys writing research-driven, audience-specific and engaging content. Her curiosity for learning and exploring makes her a suitable writer for a variety ... Read Full Bio