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

JavaScript Arrays

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 JavaScript new Keyword (Array Constructor)

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
// Creating and Initializing an array with values
let courses = new Array("HTML", "CSS", "Javascript", "React");
console.log(courses);

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

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]);

Output
HTML
CSS

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().

  • The push() method add the element to the end of the array.
  • The unshift() method add the element to the starting of the array.
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

To remove the elements from an array we have different methods like pop(), shift(), or splice().

  • The pop() method removes an element from the last index of the array.
  • The shift() method removes the element from the first index of the array.
  • The splice() method removes or replaces the element from the array.
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 Removing the last elements: " + courses);

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

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

Output

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

7. Array Length

We can get the length of the array using the array 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 loop 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. It returns new array containing 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

FeatureJavaScript ArraysJavaScript Objects
Index TypeNumeric indexes (0, 1, 2, …)Named keys (strings or symbols)
OrderOrdered collectionUnordered collection
Use CaseStoring lists, sequences, ordered dataStoring data with key-value pairs, attributes
Accessing ElementsAccessed by index (e.g., arr[0])Accessed by key (e.g., obj[“key”])
IterationTypically iterated using loops like for or forEachIterated using for…in, Object.keys(), or Object.entries()
Size FlexibilityDynamic, can grow or shrink in sizeDynamic, can add or remove key-value pairs

When to use JavaScript Arrays and Objects?

  • Use arrays when you need numeric indexing and order matters.
  • Use objects when you need named keys and the relationship between keys and values is important.

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.

JavaScript Arrays – FAQs

What is an array in JavaScript?

An array is a special type of object used to store multiple values in a single variable. Arrays can hold any combination of data types, including numbers, strings, objects, and even other arrays.

How do you create an array?

You can create an array using the array literal syntax or the Array constructor.

What is the array literal syntax?

The array literal syntax uses square brackets to enclose a comma-separated list of values.

Example: const fruits = [“apple”, “banana”, “cherry”];

What is the Array constructor?

The Array constructor creates an array by using the new Array() syntax.

Example: const fruits = new Array(“apple”, “banana”, “cherry”);

How do you access array elements?

You can access array elements using their index, which starts at 0 for the first element.

Example: const firstFruit = fruits[0];

How do you modify array elements?

You can modify array elements by assigning a new value to a specific index.

Example: fruits[0] = “orange”;



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
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 <!DOCTYPE html> <html>
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
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
Arrays in JavaScript behaves like an Object
In this article, we will learn how you check that javascript arrays behave like objects and why it happens. We will be showing the key and values in the array whether you define the key or not in an array of JavaScript. Reason for Arrays behaving like an object: In JavaScript, there is no real Array instead of that it behaves in an array because th
2 min read
How to traverse 2D arrays in JavaScript?
A two-dimensional array or simply 2D array is a format to store data in a grid format that is rows and columns format. There is no special way of declaring a 2D array in JavaScript, we can simply pass an array as an element inside another array. the array obtained in this method will be created as a 2D array. Syntax: var arr = [[...], [...], ...] E
6 min read
Destructive vs Non-Destructive Approach in JavaScript Arrays
JavaScript provides two approaches to adding elements to an array: destructive and non-destructive. Understanding the difference between them is crucial in developing efficient and error-free code. Destructive Approach: The destructive approach modifies the original array using methods like push(), pop(), shift(), unshift(), etc. One example of the
3 min read
JavaScript Program to Find Union and Intersection of Two Unsorted Arrays
In this article, we will learn how to find the Union and Intersection of two arrays. When an array contains all the elements that are present in both of the arrays, it is called a union. On the other hand, if an array has only those elements that are common in both of the arrays, then it is called an intersection. Example Input: a = [1,3,5,7,9] , b
13 min read
How to correctly use axios params with arrays in JavaScript ?
In this article, we will be going to learn about how to correctly use Axios params with arrays in Javascript. While making HTTP requests in Axios with arrays as parameters in JavaScript, one needs to serialize the array in such a way that the server can understand it easily. These are the following ways to use Axios params with arrays: Table of Con
2 min read
How Dynamic Arrays Work in JavaScript ?
A dynamic array, also known as a resizable array or a dynamic array list, is a data structure that allows its size to be changed dynamically during program execution. Unlike static arrays, which have a fixed size determined at the time of declaration, dynamic arrays can grow or shrink in size as needed. In JavaScript, dynamic arrays are typically i
3 min read
Types of Arrays in JavaScript
A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classified into multiple types: Table of Content Numeric
3 min read
JavaScript 2D Arrays
Generally, in JavaScript, we deal with one-dimensional or linear arrays that contain multiple elements of the same type stored at different memory locations with the same name. But, there are also 2D array concepts that exist in JavaScript. What are 2D Arrays?A 2D array is commonly known as an array of arrays in JavaScript. It is an array that cons
3 min read
How to Create Different Types of Arrays in JavaScript ?
In JavaScript, you can create an array using square brackets [] and optionally initialize it with values. Here are a few examples: Empty Array:Create an empty array.let emptyArray = [];Array with Values:Initialize an array with values.let numbers = [1, 2, 3, 4, 5];let fruits = ["Apple", "Banana", "Orange"];Mixed Data Types:Arrays in JavaScript can
1 min read
What is the use of reverse() method in JavaScript Arrays ?
The reverse() method in JavaScript is used to reverse the order of elements in an array. It modifies the original array and returns the reversed array. This means that the last element becomes the first, the second-to-last becomes the second, and so on. Example: Here, the reverse() the method is applied to the myArray, resulting in the original ord
1 min read
What is the use of the every() method in JavaScript Arrays ?
The every() method in JavaScript is used to check whether all elements in an array satisfy a particular condition. It returns a boolean value - true if all elements meet the specified condition, and false otherwise. Example: Here, the every() method is used to check if every element in the numbers array is even. Since all elements in this case are
1 min read
What is the use of fill() method in JavaScript Arrays ?
The fill() method in JavaScript is used to fill all the elements of an array with a static value. It modifies the original array and returns the modified array. Example: Here, the fill(0) method is applied to the myArray, which replaces all elements in the array with the value 0. C/C++ Code ; // Fill the entire array with the value 0 myArray.fill(0
1 min read
What is the use of the push() method in JavaScript Arrays ?
In JavaScript, the push() method is used to add one or more elements to the end of an array. It modifies the original array by appending the specified values. This can be particularly useful when you want to dynamically expand the size of an array or simply add new elements to the existing list. Example: Here, we are pushing newElement in myArray.
1 min read
What is the pop() method used for in JavaScript Arrays ?
The pop() method in JavaScript is used to remove the last element from an array. It alters the original array by removing and returning the last element. This can be handy when you need to manipulate arrays by taking elements off the end. Example: Here, pop() not only removes the last element (4) from the array but also returns it, allowing you to
1 min read
Median of 2 Sorted Arrays of Equal Size using JavaScript
The median is the middle element of the array. If several elements are odd then the middle element is the median and if several elements are even then the average of the two middle values is the median after arranging the array in sorted order. Below are the approaches to find the median of 2 sorted arrays of equal size using JavaScript: Table of C
3 min read
Find Common Elements In Three Sorted Arrays using JavaScript
JavaScript can be used to find the common elements in given three sorted arrays. We are given three different sorted arrays, we have to return common elements of three arrays. Example:Input array1 = [1 , 2 , 3 , 4 ,5 ] array2 = [3 , 4, 5 , 6 ,7 ]array3 = [ 3 , 4 , 7 , 8 , 9] Output [3 , 4]Below are different approaches to finding common elements pr
4 min read
JavaScript Program to find Intersection of Unsorted Arrays
JavaScript arrays are versatile structures used to store collections of elements. Oftentimes, these arrays may contain duplicates, and finding the common elements among them, known as the "intersection," becomes necessary. In this article, we'll explore various methods to efficiently find the intersection of unsorted arrays in JavaScript. Below are
3 min read
JavaScript program to Implement a Circular Queue using Arrays
A circular queue is a roundabout. When the last person in line is served, they go back to the start of the line. This way, there's no wasted space and the line keeps moving efficiently. It is an extended version of a conventional queue, a circular queue is created by joining the last element to the first element to create a circle. Operations on Ci
3 min read
JavaScript Program to Find the Distance Value between Two Arrays
We will be given two integer arrays and an integer d. The task is to calculate the distance between the two given arrays based on the given integer value. The distance value will be calculated as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d. Example:Input: arr1 = [4, 5, 8], arr2 = [10, 9,
3 min read
Sum of Middle Elements of Two Sorted Arrays using JavaScript
Given 2 sorted arrays Array1 and Array2 of size n each. Merge the given arrays and find the sum of the two middle elements of the merged array. Example: Input: array1 = [1, 3, 5] array2 = [2, 4, 6] n = 3 Output: 7 Explanation: Given two sorted arrays ar1 and ar2 of size n each: ar1 = [1, 3, 5] and ar2 = [2, 4, 6]. After merging these arrays, we get
5 min read
JavaScript Program to Find if Arrays are Disjoint or Not
Given two arrays, Our task is to check if the given two arrays are disjoint or not. Disjoint arrays in JavaScript are arrays that have no elements in common Input: arr1[] = [12, 34, 11, 9, 3] arr2[] = [2, 1, 3, 5]Output: Not Disjoint3 is common in two sets.Input: arr1[] = [12, 34, 11, 9, 3] arr2[] = [7, 2, 1, 5]Output: Yes, DisjointThere is no comm
3 min read
Median of Two Sorted Arrays of Different Sizes using JavaScript
Given two arrays, our goal is to find the median of two sorted arrays of different sizes by merging both of them. The median is the middle value of the array after dividing it into two halves. Example: Input: Arr1: [1,4,5], Arr2: [2,8,7,3]Output: Median = 4Explanation: The merged and sorted array is: ar3[] = [1,2,3,4,5,7,8] The median is 4 Table of
4 min read
JavaScript Program to Find Common Elements Between Two Sorted Arrays using Binary Search
Given two sorted arrays, our task is to find common elements in two sorted arrays then the program should return an array that contains all the elements that are common to the two arrays. The arrays can contain duplicate elements, that is, values at one index in an array can be equal to the values at another index in the array. Example: Input: arr1
3 min read
How to print unique elements from two unsorted arrays using JavaScript ?
Given two unsorted arrays, the task is to write a JavaScript program to print the unique (uncommon) elements in the two arrays. These are the way by which we print unique elements from two unsorted arrays using JavaScript: Table of Content Using for loopUsing filter() methodUsing SetsUsing for loopCreate an empty array that would store the unique e
3 min read