JavaScript Arrays

In JavaScript, an array serves as a structure that holds several values stored at distinct memory addresses while being referenced by a common name. To retrieve the values contained in an array, you can utilize the indices enclosed in square brackets, beginning from 0 and extending to the length of the array minus one ([0]…[n-1]).

Syntax

The syntax of arrays in JavaScript is as follows:

Example

const array_name = [item1, item2,…..];

Example

Example

const age = [20, 22, 21, 10, 12];

console.log(age);

Output:

Output

[ 20, 22, 21, 10, 12]

Explanation:

In the code provided above, a variable called age is declared using the const keyword, and it is initialized with an array comprising various numbers. We then output the age to the console.

How to Create Arrays in JavaScript?

There are 3 ways to create an array in JavaScript . Such as:

  • Array Literals
  • Using new keyword
  • Array Constructor
  • Array Literal

An array literal consists of a sequence of zero or more expressions, each symbolizing an element of the array, and is enclosed within square brackets ().

Syntax

An array can be initialized using an array literal through the following syntax.

Example

var arrayName=[value1, value2.....valuen];

Let's understand array literals with an example.

Example

Example

let country = [ "India", "Australia", "England" ];

for (let i = 0; i<country.length; i++ ){

console.log( country[i]);

}

Output:

Output

India

Australia

England

Explanation:

In the previous example, we declared a variable called country utilizing the let keyword, which holds the names of various countries. We employed a for loop to output all the country names. Within the for loop, we initialized the loop counter with let i = 0; and set the loop condition as i < country.length; indicating that the loop will keep running as long as the value of i is below the total number of elements in the array. The increment statement, i++, is used to raise the value of i by 1 following each iteration. Subsequently, we output the country[i] to the console.

Using a new keyword

By employing a new keyword in JavaScript, you can conveniently generate an array.

Syntax

Example

var array_name = new Array ();

Let’s explore the process of creating an array utilizing the new keyword, illustrated through an example.

Example

Example

let num;

let country = new Array ();

country[0] = "Japan";

country[1] = "Spain";

country[2] = "Germany";

for ( num = 0; num<country.length; num++ )

{

console.log( country[num]);

}

Output:

Output

Japan

Spain

Germany

Explanation:

In the preceding example, we established a variable called num utilizing the let keyword. At the outset, it holds an undefined value, which will serve as the loop counter. Additionally, we generated an empty array referred to as country, also using the let keyword. This array is devoid of any elements, and we employed the new keyword for its creation. In this context, we manually allocated values to the variables at designated indices within the array.

In this instance, num = 0 is employed to initialize the starting point at the first element of the array. The condition num < country.length is established to ensure the loop executes until num equals the total number of elements in the array. The expression num++ is used to increment num by 1 following each iteration. We then output country[num] to the console.

Array Constructor

An instance of an array can be generated by providing parameters to a constructor.

Let's explore the array constructor through an illustrative example.

Example

Example

let employee = new Array("Rohit", "Vivek", "John");  

for (let i=0;i<employee.length;i++){    

console.log(employee[i]);    

};

Output:

Output

Rohit

Vivek

John

Basic Operations on JavaScript Arrays

In JavaScript, arrays provide a variety of functions for effectively handling and processing data.

Accessing Elements of an Array

In JavaScript, to retrieve an element located at a particular index within an array, we utilize square brackets along with the corresponding index number.

Let us explore how to retrieve elements from an array through an illustrative example.

Example

Example

let cars = ["BMW", "Bugatti", "Skyline"];  

console.log(cars[1]);

Output:

Output

Bugatti

Explanation:

In the code presented above, we declared a variable called cars with the let keyword. This array holds the names of various cars. We accessed an element from a particular index by using brackets . Specifically, we logged car[1] to the console, which outputs Bugatti, as the index for Bugatti is 1.

Accessing the First Element of an Array

Accessing the first element of an array can be achieved by utilizing index 0.

Let’s explore how to retrieve the initial element of an array using a practical example.

Example

Example

let cars = ["BMW", "Bugatti", "Skyline"];  

console.log(cars[0]);

Output:

Explanation:

In the code provided above, we established a variable called cars by employing the let keyword. An array, which consists of car names, is assigned to this variable. We retrieve the first element by using the index 0, and subsequently, we output the result of car[0] to the console. Therefore, the output displayed is BMW, as BMW occupies the position at index 0.

Accessing the Last Element of an Array

To retrieve the final element of an array, we can utilize the index length minus one.

Let’s explore how to retrieve the final element of an array through an example.

Example

Example

let cars = ["BMW", "Bugatti", "Skyline"];  

let last = cars[cars.length-1];  

console.log(last);

Output:

Output

Skyline

Explanation:

In the preceding example, we created a variable called cars utilizing the let keyword. An array containing the names of various cars was assigned to this variable. Additionally, we established another variable named last and set it to cars[cars.length-1], which is used to retrieve the last index of the array. We then output the value of the last variable to the console, which yields skyline, as it resides at the last index.

Modifying the Array Elements

You can alter elements within an array by assigning a fresh value to a particular index.

Let’s explore how to alter the elements of an array through an illustrative example.

Example

Example

let cars = ["BMW", "Bugatti", "Skyline"];  

cars[1] = "Ferrari";  

console.log(cars);

Output:

Output

[ 'BMW', 'Ferrari', 'Skyline' ]

Explanation:

In the previous example, we created a variable called cars utilizing the let keyword. This variable is assigned an array that holds the names of various car brands. We then altered this array by assigning a different value to one of its elements. Specifically, car[1] = "Ferrari" is used to place "Ferrari" at the first index, effectively replacing "Bugatti" with "Ferrari". We then displayed the result in the console, which outputs an array that includes BMW, Ferrari, and Skyline. The value "Bugatti" was substituted by "Ferrari" due to our insertion at the first index.

Adding Elements to the Array

The push method allows for the addition of elements to the conclusion of an array.

Let’s explore how to incorporate elements into an array utilizing the push method.

Example

Example

let cars = ["BMW", "Bugatti", "Skyline"];  

cars.push("GTR");  

console.log(cars);

Output:

Output

[ 'BMW', 'Bugatti', 'Skyline', 'GTR' ]

Explanations:

In the preceding illustration, we created a variable called cars by employing the let keyword. This variable was assigned an array that holds the names of various cars. We made use of the push method to append a new element at the end of the array. In this case, cars.push("GTR") is used to add the new element, and the outcome is subsequently logged to the console. The result is an array comprising four elements: BMW, Bugatti, Skyline, and GTR.

Removing Elements from an Array

You can eliminate elements from an array through various methods, such as pop, shift, or splice.

Example

Example

let cars = ["BMW", "Bugatti", "Skyline"];  

cars.pop(); // removes the last element  

console.log(cars);

Output:

Output

[ 'BMW', 'Bugatti' ]

Explanation:

In the previous illustration, we created a variable called cars using the let keyword. This variable is assigned an array that holds the names of various cars. In this instance, we employed the pop method to eliminate the last item from the array. Consequently, it returns an array that consists of BMW and Bugatti.

JavaScript Array Methods

Here is a compilation of JavaScript array methods along with their corresponding explanations.

concat Method:

The concat function is employed to merge two or more arrays together.

Example

Example

const arr1 = [1, 2];

const arr2 = [3, 4];

console.log(arr1.concat(arr2));

Output:

Output

[ 1, 2, 3, 4 ]

copyWithin Method:

In JavaScript, the copyWithin function is an array method that facilitates the duplication of a series of elements from one location in an array to a different position within that same array. This method alters the original array.

Example

Example

const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

fruits.copyWithin(0, 3);

console.log(fruits);

Output:

Output

[ 'date', 'elderberry', 'cherry', 'date', 'elderberry' ]

entries Method:

In JavaScript, the entries method is utilized to generate an iterator that yields key/value pairs for every item within a collection. This method is accessible for multiple built-in objects.

Example

Example

const fruits = ["apple", "banana", "cherry"];

const fruitEntries = fruits.entries();

for (const entry of fruitEntries) {

  console.log(entry);

};

Output:

Output

[ 0, 'apple' ]

[ 1, 'banana' ]

[ 2, 'cherry' ]

every Method:

The every function in JavaScript is an array method designed to evaluate whether all items within an array satisfy a specified condition, which is defined by a provided callback function. This method yields a Boolean result.

Example

Example

const numbers = [2, 4, 6, 8, 10];

const allEven = numbers.every(number => number % 2 === 0);

console.log(allEven);

const mixedNumbers = [1, 3, 5, 7, 9, 10];

const allOdd = mixedNumbers.every(number => number % 2 !== 0);

console.log(allOdd);

Output:

Output

true

false

flat Method:

The flat function in JavaScript is employed to generate a new array that contains the elements of sub-arrays, flattened to the designated depth.

Example

Example

const nestedArray = [1, [2, 3], [4, [5, 6]]];

 const flatArray = nestedArray.flat();

 console.log(flatArray);

Output:

Output

[ 1, 2, 3, 4, [ 5, 6 ] ]

flatMap Method:

The flatMap function in JavaScript generates a new array by executing a callback function on each element of the initial array and then flattening the outcome by one level.

Example

Example

const myNumber = [ 1, 2, 3];

const myResult = myNumber.flatMap(num => [num, num * 2]);

console.log(myResult);

Output:

Output

[ 1, 2, 2, 4, 3, 6 ]

fill Method:

The fill function in JavaScript generates an array by populating it with a specified value across a defined range.

Example

Example

const myArray = new Array(5).fill(0);

console.log(myArray);

Output:

Output

[0, 0, 0, 0, 0];

from Method:

The from function in JavaScript generates a new instance from any iterable, which can include objects, arrays, and strings.

Example

Example

const myStr = "Hello JavaScript";

const myResult = Array.from(myStr);

console.log(myResult);

Output:

Output

[

  'H', 'e', 'l', 'l',

  'o', ' ', 'J', 'a',

  'v', 'a', 'S', 'c',

  'r', 'i', 'p', 't'

]

filter Method:

The filter function in JavaScript creates a new array consisting of elements that meet the specified criteria.

Example

Example

const myNum = [1, 2, 3, 4, 5, 6];

const myEvenNumber = myNum.filter(num => num % 2 === 0);

console.log(myEvenNumber);

Output:

Output

[2, 4, 6]

find Method:

In JavaScript, the find function iterates over an array and returns the initial element that meets the defined criteria.

Example

Example

const myNumbers = [3, 7, 12, 18, 5];

const myResult = myNumbers.find(num => num > 10);

console.log(myResult);

Output:

findIndex Method:

In JavaScript, the findIndex function is utilized to locate the index of the first element within an array that meets a specified criterion.

Example

Example

const myNumbers = [3, 7, 12, 18, 5];

const myResult = myNumbers.findIndex(num => num > 10);

console.log(myResult);

Output:

forEach Method:

The forEach method in JavaScript executes a specified function for every element in an array, performing the operation sequentially for each item.

Example

Example

const myNumbers = [1, 2, 3, 4, 5];

myNumbers.forEach(num => {

console.log(num);

});

Output:

Output

1

2

3

4

5

includes Method:

The includes function in JavaScript is utilized to determine if a given array holds a specific element. It subsequently returns a boolean value indicating the presence or absence of that element.

Example

Example

const myName = ['John', 'Shiv', 'Ankit'];

console.log(myName.includes('Shiv'));

Output:

indexOf Method:

The indexOf function for an array searches for the initial occurrence of a specified value and provides the index of that value.

Example

Example

const myFruits = ['apple', 'cherry', 'banana'];

console.log(myFruits.indexOf('cherry'));

Output:

isArray Method:

The isArray function associated with an array serves the purpose of determining if a specified value is an array. It yields a Boolean result.

Example

Example

const myFruits = ['apple', 'banana', 'cherry'];

console.log(Array.isArray(myFruits));

Output:

join Method:

The join function of an array is employed to concatenate the elements of an array into a single string.

Example

Example

const words = ['Hello', 'world', '!'];

const sentence = words.join(' ');

console.log(sentence);

Output:

Output

Hello world !

keys Method:

The keys function of an array is used to generate a new array iterator that provides the keys for each index present in the specified input array.

Example

Example

let arr = [5, 6, 10];

let iterator = arr.keys();

for (let key of iterator) {

console.log(key);

};

Output:

Output

0

1

2

lastIndexOf Method:

The lastIndexOf function searches for the most recent occurrence of a specified element and provides the index of that element.

Example

Example

const colors = ['red', 'blue', 'green', 'blue', 'yellow'];

console.log(colors.lastIndexOf('blue'));

Output:

map Method:

The map function of an array serves as a higher-order function that generates a new array by applying a specified callback function to every individual element.

Example

Example

let myNumbers = [1, 2, 3, 4, 5];

console.log(myNumbers.map(num => num * 2));

Output:

Output

[2, 4, 6, 8, 10]

of Method:

The of function within an array is utilized to generate a new array that contains the specified arguments.

Example

Example

let myStudents = Array.of("Anirudh", "Angel", "Ayush");

console.log(myStudents);

Output:

Output

[ 'Anirudh', 'Angel', 'Ayush' ]

pop Method:

The pop function for arrays serves the purpose of eliminating the final element from an array and provides the removed element as a return value.

Example

Example

const fruitsName = ["apple", "banana", "orange"];

console.log (fruitsName.pop());

Output:

Output

orange

push Method:

The push function within an array appends a new element to the conclusion of the array.

Example

Example

const  myFruits = ["Apple", "Banana", "Orange"];

myFruits.push("Grape");

console.log(myFruits);

Output:

Output

[ 'Apple', 'Banana', 'Orange', 'Grape' ]

reverse Method:

The reverse function for an array is employed to invert the order of the elements within that array.

Example

Example

const myArray = [ 'Apple', 'Banana', 'Orange', 'Grape' ];

myArray.reverse();

console.log(myArray);

Output:

Output

[ 'Grape', 'Orange', 'Banana', 'Apple' ]

reduce(function, initial) Method:

This technique applied to an array is designed to execute a user-defined function for every individual element within the array.

Example

Example

const myNumber = [1, 2, 3, 4, 5];

const sumReducer = (accumulator, currentValue) => {

return accumulator + currentValue;

};

const  result = myNumber.reduce(sumReducer, 0);

console.log(result);

Output:

reduceRight Method:

The reduceRight function for arrays is employed to apply a reducer function to every element within the array.

Example

Example

const  myWords = ["world", ' ', "hello"];

const mySentence = myWords.reduceRight((accumulator, word ) => accumulator + word);

console.log(mySentence);

Output:

Output

hello world

some Method:

The some method in JavaScript is employed to determine if at least one element within the array meets the criteria specified by a provided function.

Example

Example

const myNumbers = [1, 2, 3, 4, 5, 6];

const result = myNumbers.some(num =>num %2 === 0);

console.log(result);

Output:

shift Method:

The shift function on an array is employed to eliminate the initial element of the array and subsequently return the element that has been removed.

Example

Example

let myColors= ["red", "green", "blue"];

let myResult = myColors.shift()

console.log(myColors);

Output:

Output

[ 'green', 'blue' ]

slice Method:

The slice function applied to an array is used to extract a segment of that array.

Example

Example

const myFruits =  ['apple', 'banana', 'orange', 'grape', 'kiwi'];

const result = myFruits.slice(0, 3);

console.log(result);

Output:

Output

[ 'apple', 'banana', 'orange' ]

sort Method:

The sort function for arrays is employed to arrange the elements of an array in alphabetical order.

Example

Example

let myArray = ["ReactJS", "Python", "MySQL"];

console.log(myArray.sort());

Output:

Output

[ 'MySQL', 'Python', 'ReactJS' ]

splice Method:

The splice function associated with arrays serves the purpose of inserting, deleting, and substituting elements within an array.

Example

Example

let myFruits = ["Apple", "Banana", "Cherry", "Date"];

let removedElement = myFruits.splice(2, 1);

console.log(myFruits);

console.log(removedElement);

Output:

Output

[ 'Apple', 'Banana', 'Date' ]

[ 'Cherry' ]

toLocaleString Method:

It provides a string representation of an object that is sensitive to the language context.

Example

Example

let date = new Date("2025-09-20T12:30:00");

// US English

console.log(date.toLocaleString("en-US"));

// British English (UK)

console.log(date.toLocaleString("en-GB"));

Output:

Output

9/20/2025, 12:30:00 PM

9/20/2025, 12:30:00 PM

toString Method:

This is an inherent method employed to transform a value or object into its corresponding string representation.

Example

Example

let colors = ["Red", "Green", "Blue"];

console.log(typeof colors.toString());

Output:

Output

string

unshift Method:

The unshift function in JavaScript is employed to add elements to the start of an array.

Example

Example

const myFruits = ["banana", "orange"];

myFruits.unshift("cherry", "apple");

console.log(myFruits);

Output:

Output

[ 'cherry', 'apple', 'banana', 'orange' ]

values Method:

In JavaScript, the values method is employed to generate a new array iterator object that holds the values corresponding to each index.

Example

Example

const myArray = ['Apple', 'Banana', 'Grapes', 'cherry'];

const iterator = myArray.values();

for (let value of iterator) {

console.log(value);

};

Output:

Output

Apple

Banana

Grapes

Cherry
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copyWithin() It copies the part of the given array with its own elements and returns the modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided function conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till the specified depth.
flatMap() It maps all array elements via mapping function, then flattens the result into a new array.
fill() It fills elements into an array with static values.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided function conditions.
find() It returns the value of the first element in the given array that satisfies the specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the first match.
isArray() It tests if the passed value is an array.
join() It joins the elements of an array as a string.
keys() It creates an iterator object that contains only the keys of the array, then loops through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type of argument.
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of the given array.
reduce(function, initial) It executes a provided function for each value from left to right and reduces the array to a single value.
reduceRight() It executes a provided function for each value from right to left and reduces the array to a single value.
some() It determines if any element of the array passes the test of the implemented function.
shift() It removes and returns the first element of an array.
slice() It returns a new array containing a copy of the part of the given array.
sort() It returns the elements of the given array in a sorted order.
splice() It adds/removes elements to/from the given array.
toLocaleString() It returns a string containing all the elements of a specified array.
toString() It converts the elements of a specified array into string form, without affecting the original array.
unshift() It adds one or more elements at the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.

Conclusion:

JavaScript arrays represent a crucial data structure within the language. They enable the storage of numerous values within a single variable and provide users with an array of built-in methods for tasks such as adding, deleting, modifying, sorting, and iterating through elements. Arrays can hold various data types including numbers, strings, objects, and more. This article comprehensively explores all aspects of JavaScript arrays. Whether you are new to programming or a seasoned developer, you will find this article beneficial.

Frequently Asked Questions (FAQs):

  1. What constitutes an array in JavaScript? In what manner can we define an array?

In JavaScript, an array functions as an object designed to contain numerous values within a single variable. It is capable of holding values of any data type, and each value can be retrieved using an index, starting with the initial index at 0.

Here is the syntax provided for declaring a variable:

Example

const array_name = [item1, item2,…..];
  1. What are the methods for accessing the elements within an array?

Elements within an array can be accessed through their respective indices. The index for the initial element is 0, the index for the subsequent element is 1, and this pattern continues accordingly.

Example

Example

let fruits = ['apple', 'banana', 'cherry'];

console.log(fruits[0]);

console.log(fruits[1]);

console.log(fruits[2]);

Output:

To determine whether a variable is classified as an array, you can employ the Array.isArray method in JavaScript. This function reliably evaluates the given variable and returns a boolean value indicating its status as an array.

Here's a brief illustration of how to utilize this method:

Example

let myArray = [1, 2, 3];
let myVariable = "Hello, World!";

console.log(Array.isArray(myArray)); // Output: true
console.log(Array.isArray(myVariable)); // Output: false

In the example provided, Array.isArray(myArray) returns true, confirming that myArray is indeed an array, whereas myVariable is determined not to be an array, resulting in false.

This method is particularly useful for validating data types in situations where you need to ascertain the structure of a variable before performing operations that are specific to arrays.

To determine whether a variable is an array, we can use the Array.isArray function. This function yields true if the variable in question is indeed an array and returns false if it is not.

Example

Example

let fruits = ['apple', 'banana'];

console.log(Array.isArray(fruits));



let notAnArray = 'apple';

console.log(Array.isArray(notAnArray));

Output:

Output

true

false
  1. What does the length attribute of an array signify?

In JavaScript, the length attribute of an array is employed to indicate the total count of elements contained within that array. This property is dynamic in nature, meaning it can automatically adjust to reflect any modifications made to the array.

Example

Example

let fruits = ['apple', 'banana', 'cherry'];

console.log(fruits.length);
  1. In what ways can we utilize the forEach method?

The forEach method serves to execute a specified function once for every element in an array. It accepts a callback function as a parameter, which is invoked for each element, providing the element itself, its index, and the complete array as arguments.

The forEach function neither produces a new array nor alters the existing array.

Example

Example

let fruits = ['apple', 'banana', 'cherry'];

fruits.forEach((fruit, index) => {

  	console.log(`Fruit at index ${index} is ${fruit}`);

});

Output:

Output

Fruit at index 0 is apple

Fruit at index 1 is banana

Fruit at index 2 is cherry
  1. What distinguishes for...of loops from for...in loops when working with arrays?

The for...of loop traverses the values contained within an array, while the for...in loop is designed to iterate through the keys (or indexes) of that array. Typically, the for...of loop is favored for array operations as it allows for direct access to the elements, whereas the for...in loop is more appropriate for enumerating the properties of objects.

  1. What is the functionality of the find method?

The find function retrieves the value of the initial element within the array that meets the criteria specified by the given testing function. In instances where no elements fulfill the conditions of the testing function, the result is undefined.

Example

Example

let numbers = [1, 2, 3, 4, 5];

let foundNumber = numbers.find(num => num > 3);

console.log(foundNumber);
  1. What are the methods to combine two arrays using the concat function and the spread operator?

The concat function generates a new array that merges the elements of two arrays, whereas the spread operator facilitates the creation of a new array by dispersing the elements from both arrays.

Example

Example

let fruits = ['apple', 'banana'];

let moreFruits = ['cherry', 'mango'];



// Using concat method

let allFruits1 = fruits.concat(moreFruits);

console.log(allFruits1);





// Using spread operator

let allFruits2 = [...fruits, ...moreFruits];

console.log(allFruits2);

Output:

Output

[ 'apple', 'banana', 'cherry', 'mango' ]

[ 'apple', 'banana', 'cherry', 'mango' ]

Input Required

This code uses input(). Please provide values below: