CS Engineering Gyan

JavaScript Arrays

Arrays are one of the most important data structures in JavaScript. An array allows developers to store multiple values inside a single variable.

Instead of creating separate variables for every value, arrays provide an organized way to collect and manage related data together.

Arrays are widely used in web development for storing lists of users, products, marks, images, messages, and many other types of information.


What is an Array in JavaScript?

An array is a special type of object that stores multiple values in a single variable. Each value inside an array is called an element.

Every element in an array has a unique position called an index. JavaScript array indexing starts from 0.

Example


let fruits = ["Apple", "Banana", "Mango"];

In this example, three values are stored inside one array named fruits.


Why are Arrays Important?

Arrays make data management easier by allowing programmers to store and process multiple values efficiently.

Advantages of Arrays


Creating Arrays in JavaScript

JavaScript provides different ways to create arrays. The most common method is using square brackets [].

Method 1: Using Array Literal


let numbers = [10,20,30,40];

This is the simplest and most commonly used way to create an array.


Method 2: Using Array Constructor


let numbers = new Array(10,20,30,40);

The Array constructor can also be used to create arrays, but developers usually prefer array literals because they are shorter and easier to understand.


Accessing Array Elements

Array elements are accessed using their index number. The first element always has index 0.

Example


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


document.write(colors[0]);

Output


Red


Array Indexing in JavaScript

Index Value
0 Red
1 Green
2 Blue

Changing Array Elements

Array values can be modified by accessing their index and assigning a new value.

Example

let fruits = ["Apple","Banana","Mango"];

fruits[1] = "Orange";

document.write(fruits);

Output

Apple,Orange,Mango

Finding Array Length

The length property is used to find the total number of elements present in an array.

Example

let subjects = [

"JavaScript",

"Python",

"Java",

"SQL"

];

document.write(subjects.length);

Output

4

Adding Elements to an Array

JavaScript provides different methods to add new elements to arrays.

Using push() Method

The push() method adds a new element at the end of an array.

Example

let numbers = [1,2,3];

numbers.push(4);

document.write(numbers);

Output


1,2,3,4


Using unshift() Method

The unshift() method adds an element at the beginning of an array.

Example

let fruits = ["Banana","Mango"];

fruits.unshift("Apple");

document.write(fruits);

Output


Apple,Banana,Mango


Removing Elements from Array

JavaScript provides methods to remove elements from arrays.

Using pop() Method

The pop() method removes the last element from an array.

Example

let numbers = [10,20,30];

numbers.pop();

document.write(numbers);

Output


10,20


Using shift() Method

The shift() method removes the first element from an array.

Example

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

colors.shift();

document.write(colors);

Output


Green,Blue



JavaScript Array Methods

JavaScript provides many built-in array methods that help developers perform different operations such as adding, removing, searching, sorting, and modifying array elements.

Using array methods makes code shorter, cleaner, and easier to maintain.


concat() Method in JavaScript

The concat() method is used to combine two or more arrays. It does not modify the original arrays; instead, it returns a new array containing all elements.

Syntax

array1.concat(array2);

Example


let first = [1,2,3];
let second = [4,5,6];

let result = first.concat(second);

document.write(result);

Output


1,2,3,4,5,6


slice() Method

The slice() method is used to extract a portion of an array. It returns a new array without changing the original array.

Syntax


array.slice(start,end);

Example


let fruits = ["Apple","Banana","Mango","Orange"];

let result = fruits.slice(1,3);

document.write(result);

Output


Banana,Mango

The starting index is included, but the ending index is not included.


splice() Method

The splice() method is used to add, remove, or replace elements in an array. Unlike slice(), splice() changes the original array.

Syntax


array.splice(index, number, item1, item2);


Example: Removing Elements Using splice()


let numbers = [10,20,30,40];

numbers.splice(1,2);

document.write(numbers);

Output


10,40


Example: Adding Elements Using splice()


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

colors.splice(1,0,"Green");

document.write(colors);

Output


Red,Green,Blue


Searching Elements in Arrays

JavaScript provides several methods to find elements inside an array.


indexOf() Method

The indexOf() method returns the position of the first occurrence of an element in an array.

Example

let fruits = ["Apple","Banana","Mango"];

let position = fruits.indexOf("Mango");

document.write(position);

Output


2

If the element does not exist, indexOf() returns -1.


includes() Method

The includes() method checks whether a specific value exists in an array. It returns true or false.

Example

let numbers = [10,20,30];

document.write(numbers.includes(20));

Output

true

find() Method

The find() method returns the first element that satisfies a given condition.

Example

let numbers = [5,10,15,20];

let result = numbers.find(function(value){

    return value > 10;
});

document.write(result);

Output


15


Sorting Arrays

The sort() method is used to arrange array elements in ascending or alphabetical order.

Example

let names = ["Rahul","Amit","Neha"];

names.sort();

document.write(names);

Output


Amit,Neha,Rahul


Sorting Numbers Correctly

By default, JavaScript converts numbers into strings while sorting. A comparison function should be used for proper numerical sorting.

Example

let numbers = [50,10,30,20];
numbers.sort(function(a,b)
{

    return a-b;

});

document.write(numbers);

Output

10,20,30,50

reverse() Method

The reverse() method reverses the order of array elements.

Example

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

numbers.reverse();

document.write(numbers);

Output

4,3,2,1

join() Method

The join() method converts array elements into a single string separated by a specified separator.

Example

let fruits = ["Apple","Banana","Mango"];

let result = fruits.join("-");

document.write(result);

Output


Apple-Banana-Mango


Array Iteration in JavaScript

Iteration means accessing each element of an array one by one. JavaScript provides multiple ways to iterate arrays.


Using for Loop with Arrays

Example

let fruits = ["Apple","Banana","Mango"];

for(let i=0; i <= fruits.length; i++)
{
    document.write(fruits[i]);
}

Output

Apple

Banana

Mango


forEach() Method

The forEach() method executes a function once for every element of an array.

Syntax

array.forEach(function(element)
{

});

Example

let numbers = [10,20,30];

numbers.forEach(function(value)
{

    document.write(value);

});

Output

10
20
30

map() Method

The map() method creates a new array by applying a function to every element of an existing array.

Example

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

let result = numbers.map(function(value)
{

    return value * 2;

});
document.write(result);

Output

2,4,6,8

filter() Method

The filter() method creates a new array containing only elements that satisfy a specific condition.

Example

let numbers = [5,10,15,20];
let result = numbers.filter(function(value)
{
    return value >= 10;
});
document.write(result);

Output

10,15,20

reduce() Method

The reduce() method reduces all array elements into a single value. It is commonly used for calculations such as total, average, and counting.

Example

let numbers = [10,20,30];
let total = numbers.reduce(function(sum,value)
{
    return sum + value;

},0);
document.write(total);

Output

60


Multidimensional Arrays in JavaScript

A multidimensional array is an array that contains one or more arrays as its elements. It is useful when data needs to be stored in a table-like structure with rows and columns.

Multidimensional arrays are commonly used for storing matrices, game boards, student records, and other structured data.

Example: Two Dimensional Array

let marks = [    [80,90,70],    [75,85,95],    [60,70,88]];

document.write(marks[0][1]);

Output

90

In this example, the first index selects the inner array and the second index selects the element inside that array.


Looping Through Multidimensional Arrays

Nested loops are generally used to access every element of a multidimensional array.

Example

let numbers = [    [1,2,3],    [4,5,6],    [7,8,9]];

for(let i = 0; i < numbers.length; i++)
{
    for(let j = 0; j < numbers[i].length; j++)
    {
        document.write(numbers[i][j]);

    }
}

Output


1
2
3
4
5
6
7
8
9


Array of Objects in JavaScript

JavaScript arrays can store objects as elements. This structure is commonly used when handling real-world data such as users, products, employees, and students.

Example

let students = [
{
name:"Rahul",
age:20
},
{
name:"Amit",
age:21
}
];
document.write(students[0].name);

Output

Rahul

Accessing Object Data Inside Arrays

let products = [
{
id:101,
name:"Laptop",
price:50000
},
{
id:102,
name:"Mobile",
price:20000
}
];
document.write(products[1].price);

Output

20000

Array Destructuring in JavaScript

Array destructuring allows developers to extract values from arrays and store them into separate variables using a simple syntax.

Syntax

let [variable1, variable2] = array;

Example: Array Destructuring

let colors = ["Red","Green","Blue"];
let [first, second, third] = colors;
document.write(first);

Output

Red

Destructuring makes code cleaner and easier to read when working with array values.


Spread Operator with Arrays

The spread operator (...) expands array elements into individual values. It is useful for copying arrays and combining multiple arrays.

Example: Copy Array

let numbers = [10,20,30];
let copy = [...numbers];
document.write(copy);

Output

10,20,30

Combining Arrays Using Spread Operator

let first = [1,2,3];
let second = [4,5,6];
let result = [...first,...second];
document.write(result);

Output

1,2,3,4,5,6

Rest Operator with Arrays

The rest operator also uses three dots (...). It collects remaining elements into a new array.

Example

let numbers = [10,20,30,40,50];
let [first,...remaining] = numbers;
document.write(remaining);

Output

20,30,40,50

Copying Arrays in JavaScript

There are different ways to create copies of arrays in JavaScript.

Using Spread Operator

let original = [1,2,3];
let copy = [...original];

Using slice() Method

let original = [1,2,3];
let copy = original.slice();

Using concat() Method

let original = [1,2,3];
let copy = [].concat(original);

Comparing Arrays

Arrays are objects in JavaScript. Two arrays with the same values are not considered equal because they are stored at different memory locations.

Example

let a = [1,2,3];
let b = [1,2,3];
console.log(a == b);

Output

false

Removing Duplicate Values from Array

The Set object can be used with arrays to remove duplicate values.

Example

let numbers = [10,20,20,30,30];
let unique = [...new Set(numbers)];
document.write(unique);

Output

10,20,30

Checking Array Type

The typeof operator returns object for arrays. Therefore, JavaScript provides the Array.isArray() method to check whether a value is an array.

Example

let data = [10,20,30];
document.write(Array.isArray(data));

Output

true

Real-World Applications of JavaScript Arrays

Arrays are used in almost every type of web application because they help store and manage collections of data.


Common Mistakes While Using Arrays


Best Practices for JavaScript Arrays


JavaScript Arrays Interview Questions

  1. What is an array in JavaScript?
  2. How do you create an array?
  3. What is array indexing?
  4. Why does array indexing start from zero?
  5. Explain push() and pop() methods.
  6. What is the difference between slice() and splice()?
  7. Explain map() method.
  8. Explain filter() method.
  9. What is reduce() method used for?
  10. How can you remove duplicate values from an array?
  11. What is a multidimensional array?
  12. How do you check whether a value is an array?
  13. What is array destructuring?
  14. Explain spread operator with arrays.
  15. What is the difference between forEach() and map()?

Summary

JavaScript arrays are powerful data structures that allow developers to store multiple values in a single variable. Arrays provide many useful methods for adding, removing, searching, sorting, and processing data efficiently.

Important array concepts include indexing, array methods, iteration, multidimensional arrays, arrays of objects, destructuring, spread operator, and advanced array operations.

A strong understanding of arrays is necessary for learning advanced JavaScript topics such as objects, DOM manipulation, APIs, asynchronous programming, and modern JavaScript frameworks.


← Previous: JavaScript Functions Next: JavaScript Objects →
Home Visit Our YouTube Channel