JavaScript Array – How to Use Them?

JavaScript Array – How to Use Them?

7 mins read1.1K Views Comment
clickHere
Chanchal
Chanchal Aggarwal
Senior Executive Content
Updated on Nov 2, 2022 17:20 IST

JavaScript array is an object that holds multiple values at once. This blog will throw light on its related concepts such as how to declare and initialize JavaScript array. Also, how to access and change array elements.

2022_11_Arrays-in-Javascript.jpg

Introduction
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 us to organize and condense our 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.

Table of Contents

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

Example:

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

A JavaScript array has the following characteristics:

  • JavaScript Array object allows you to store multiple values in a single variable.
  • Values of 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 have an increasing size. In other words, defining the array size in advance is not necessary.

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 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, …];

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 Certified JavaScript Developer? Check these Free Courses and Certifications

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 in two ways, array literal and Array constructor syntax.

  1. Array Literal

A list of elements present within square brackets in an array is known as Array Literals. 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

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, which consisted of the indices 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 kind of issues can be managed by using the push() method, which include 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, if you use the unshift() method, it will add 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 of the 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, 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.  

Download this article as PDF to read offline

Download as PDF
clickHere
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

Comments

We use cookies to improve your experience. By continuing to browse the site, you agree to our Privacy Policy and Cookie Policy.