The Wayback Machine - https://web.archive.org/web/20240619045459/https://www.geeksforgeeks.org/javascript-arrays/
Open In App

JavaScript Arrays

Last Updated : 29 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An array in JavaScript is a data structure used to store multiple values in a single variable. It can hold various data types and allows for dynamic resizing. Elements are accessed by their index, starting from 0.

JavaScript Arrays

JavaScript Array

You have two ways to create JavaScript Arrays: using the Array constructor or the shorthand array literal syntax, which is just square brackets. Arrays are flexible in size, so they can grow or shrink as you add or remove elements.

Basic Terminologies of JavaScript Array

  • Array: A data structure in JavaScript that allows you to store multiple values in a single variable.
  • Array Element: Each value within an array is called an element. Elements are accessed by their index.
  • Array Index: A numeric representation that indicates the position of an element in the array. JavaScript arrays are zero-indexed, meaning the first element is at index 0.
  • Array Length: The number of elements in an array. It can be retrieved using the length property.

Declaration of an Array

There are basically two ways to declare an array i.e. Array Literal and Array Constructor.

1. Creating an Array using Array Literal

Creating an array using array literal involves using square brackets [] to define and initialize the array. This method is concise and widely preferred for its simplicity.

Syntax:

let arrayName = [value1, value2, ...];

Example:

Javascript
// Creating an Empty Array
let names = [];
console.log(names);

// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];

console.log(courses);

Output
[]
[ 'HTML', 'CSS', 'Javascript', 'React' ]

2. Creating an Array using Array Constructor (JavaScript new Keyword)

The “Array Constructor” refers to a method of creating arrays by invoking the Array constructor function. This approach allows for dynamic initialization and can be used to create arrays with a specified length or elements.

Syntax:

let arrayName = new Array();

Example:

javascript
// Declaration of an empty array 
// using Array constructor
let names = new Array();
console.log(names);

// Creating and Initializing an array with values
let courses = new Array("HTML", "CSS", "Javascript", "React");
console.log(courses);

// Initializing Array while declaring
let arr = new Array(3);
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
console.log(arr);

Output
[]
[ 'HTML', 'CSS', 'Javascript', 'React' ]
[ 10, 20, 30 ]

Note: Both the above methods do exactly the same. Use the array literal method for efficiency, readability, and speed.

Basic Operations on JavaScript Arrays

1. Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the arrays starts with 0.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];

// Accessing Array Elements
console.log(courses[0]);
console.log(courses[1]);
console.log(courses[2]);
console.log(courses[3]);

Output
HTML
CSS
Javascript
React

2. Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of array using the index number.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing First Array Elements
let firstItem = courses[0];

console.log("First Item: ", firstItem);

Output
First Item:  HTML

3. Accessing the Last Element of an Array

We can access the last array element using [array.length – 1] index number.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing Last Array Elements
let lastItem = courses[courses.length - 1];

console.log("First Item: ", lastItem);

Output
First Item:  React

4. Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their corresponding index.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
console.log(courses);

courses[1]= "Bootstrap";
console.log(courses);

Output
[ 'HTML', 'CSS', 'Javascript', 'React' ]
[ 'HTML', 'Bootstrap', 'Javascript', 'React' ]

5. Adding Elements to the Array

Elements can be added to the array using methods like push() and unshift().

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];

// Add Element to the end of Array
courses.push("Node.js");

// Add Element to the beginning
courses.unshift("Web Development");

console.log(courses);

Output
[ 'Web Development', 'HTML', 'CSS', 'Javascript', 'React', 'Node.js' ]

6. Removing Elements from an Array

Remove elements using methods like pop(), shift(), or splice().

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
console.log("Original Array: " + courses);

// Removes and returns the last element
let lastElement = courses.pop();
console.log("After Removed the last elements: " + courses);

// Removes and returns the first element
let firstElement = courses.shift();
console.log("After Removed the First elements: " + courses);

// Removes 2 elements starting from index 1
courses.splice(1, 2);
console.log("After Removed 2 elements starting from index 1: " + courses);

Output

Original Array: HTML,CSS,Javascript,React,Node.js
After Removed the last elements: HTML,CSS,Javascript,React
After Removed the First elements: CSS,Javascript,React
After Removed 2 elements starting from index 1: CSS

7. Array Length

Get the length of an array using the length property.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];

let len = courses.length;

console.log("Array Length: " + len);

Output
Array Length: 5

8. Increase and Decrease the Array Length

We can increase and decrease the array length using the JavaScript length property.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];

// Increase the array length to 7
courses.length = 7;

console.log("Array After Increase the Length: ", courses);

// Decrease the array length to 2
courses.length = 2;
console.log("Array After Decrease the Length: ", courses)

Output
Array After Increase the Length:  [ 'HTML', 'CSS', 'Javascript', 'React', 'Node.js', <2 empty items> ]
Array After Decrease the Length:  [ 'HTML', 'CSS' ]

9. Iterating Through Array Elements

We can iterate array and access array elements using for and forEach loop.

Example: It is an example of for loop.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Iterating through for loop
for (let i = 0; i < courses.length; i++) {
    console.log(courses[i])
}

Output
HTML
CSS
JavaScript
React

Example: It is the example of Array.forEach() loop.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Iterating through forEach loop
courses.forEach(function myfunc(elements) {
    console.log(elements);
});

Output
HTML
CSS
JavaScript
React

10. Array Concatenation

Combine two or more arrays using the concat() method. Ir returns new array conaining joined arrays elements.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
let otherCourses = ["Node.js", "Expess.js"];

// Concatenate both arrays
let concateArray = courses.concat(otherCourses);

console.log("Concatenated Array: ", concateArray);

Output
Concatenated Array:  [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js', 'Expess.js' ]

11. Conversion of an Array to String

We have a builtin method toString() to converts an array to a string.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Convert array ot String
console.log(courses.toString());

Output
HTML,CSS,JavaScript,React

12. Check the Type of an Arrays

The JavaScript typeof operator is used ot check the type of an array. It returns “object” for arrays.

Javascript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Check type of array
console.log(typeof courses);

Output
object

Difference Between JavaScript Arrays and Objects

  • JavaScript arrays use indexes as numbers.
  • objects use indexes as names..

When to use JavaScript Arrays and Objects?

  • Arrays are used when we want element names to be numeric.
  • Objects are used when we want element names to be strings.

Recognizing a JavaScript Array

There are two methods by which we can recognize a JavaScript array:

Below is an example showing both approaches:

Javascript
const courses = ["HTML", "CSS", "Javascript"];
console.log("Using Array.isArray() method: ", Array.isArray(courses))
console.log("Using instanceof method: ", courses instanceof Array)

Output
Using Array.isArray() method:  true
Using instanceof method:  true

Note: A common error is faced while writing the arrays:

const numbers = [5]
// and
const numbers = new Array(5) 
Javascript
const numbers = [5]
console.log(numbers)

The above two statements are not the same.

Output: This statement creates an array with an element ” [5] “.

[5]
Javascript
const numbers = new Array(5) 
console.log(numbers)

Output
[ <5 empty items> ]

JavaScript Array Complete Reference

We have a complete list of Javascript Array, to check those please go through this JavaScript Array Reference article. It contains a detailed description and examples of all Array Properties and Methods.

JavaScript Array Examples

JavaScript Array examples contain a list of questions that are majorly asked in interviews. Please check this article JavaScript Array Examples for more detail.

JavaScript CheatSheet

We have a Cheat Sheet on Javascript where we have covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



Previous Article
Next Article

Similar Reads

How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional structures. Such nested arrays can represent various dat
3 min read
New features of JavaScript Arrays with ES2015
In this article we will be discussing the new additions in ES2015 which substantially improves the way we work with Arrays in JavaScript. Array Destructuring Array destructuring allows us to assign values to variables from an array using syntax similar to the array itself. Let’s look at the code below where we have an array of animals. We need to a
4 min read
Converting JavaScript Arrays into CSVs and Vice-Versa
Converting Arrays into CSVs: Given an array in JavaScript and the task is to obtain the CSVs or the Comma Separated Values from it. Now, JavaScript being a versatile language provides multiple ways to achieve the task. Some of them are listed below. Using the toString() methodUsing valueof() MethodUsing the join() functionUsing the split() function
2 min read
JavaScript | JSON Arrays
The JSON Arrays is similar to JavaScript Arrays. Syntax of Arrays in JSON Objects: // JSON Arrays Syntax { "name":"Peter parker", "heroName": "Spiderman", "friends" : ["Deadpool", "Hulk", "Wolverine"] } Accessing Array Values: The Array values can be accessed using the index of each element in an Array. C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt;
2 min read
How to cartesian product of 2 arrays using JavaScript ?
The task is to compute the cartesian product of two JavaScript arrays with the help of JavaScript. Here are a few techniques discussed. Approach 1: Create a new array.Traverse the first array by the outer loop and the second array by the inner loop.In the inner loop, Concatenate the first array element with the second array element and push it into
2 min read
Find the common elements of more than two JavaScript arrays ?
Given an HTML document having multiple arrays with some elements and the task is to get the common elements from arrays with the help of JavaScript. There are two approaches that are discussed below. Approach 1: First get the arrays in 2-dimensional format then take the first array by shift() method and then filter out the elements from the first a
3 min read
How to Merge/Combine Arrays using JavaScript ?
There are many ways of merging arrays in JavaScript. We will discuss two problem statements that are commonly encountered in merging arrays: Merge without removing duplicate elements. Merge after removing the duplicate elements. Merge without removing duplicate elements: We will first begin with three arrays and merge them. Later, we will generaliz
5 min read
How to calculate greatest common divisor of two or more numbers/arrays in JavaScript ?
In this article, we are given two or more numbers/array of numbers and the task is to find the GCD of the given numbers/array elements in JavaScript. Examples: Input : arr[] = {1, 2, 3} Output : 1 Input : arr[] = {2, 4, 6, 8} Output : 2 The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can al
2 min read
Javascript Program to Maximize count of corresponding same elements in given Arrays by Rotation
Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples: Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9, 5, 6 } Output: 5 Explanation: By performing cycli
3 min read
Javascript Program for Find k pairs with smallest sums in two arrays
Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] Explanation: The first 3 pairs are returned from th
3 min read