Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is an array in JavaScript?
2.1.
Example
3.
Creating an array using array literal
3.1.
JavaScript
4.
Creating instance of Array directly (using new keyword)
4.1.
JavaScript
5.
Using an Array constructor (using new keyword)
5.1.
JavaScript
6.
JavaScript Array Methods
7.
Frequently Asked Questions
7.1.
What is an array in JavaScript?
7.2.
How many types of arrays are there in JS?
7.3.
What are two forms of array?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Array in Javascript

Author Sagar Mishra
2 upvotes
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

JavaScript Array is a variable that can hold elements of various data types and is indexed starting from zero.

Similarly, JS (JavaScript) arrays significantly treat many variables as a single identity. An array is a group of items with the same data types.

Array in javascript

This blog will discuss the arrays in JS in detail. Let's start.

Also See, Javascript hasOwnProperty

What is an array in JavaScript?

In Javascript, an Array is used to store multiple values in a single variable. It is a data structure that stores a collection of values with different data types, such as numbers, strings, or objects. The array elements are indexed starting from 0, and they can be accessed via these indexes using various methods in Javascript.

Unlike C or C++, where an array is a variable or a data type, an array is an object in Javascript

Objects in JavaScript are described as an unordered collection of connected data, of primitive or reference types, in the form of "key: value" pairs. In the context of an object, these keys can be variables or functions, referred to as properties and methods, respectively.

Let's take an example of an object in JS.

Example

let organisation= {
    name: "Coding Ninjas",
    location: "Delhi",
    established: "2016"
}
console.log(organisation);


Output:

arrays output

You can store keyed collections of values in objects. That's all right. However, we often require an ordered collection, with first, second, third elements, and so on. 

For example, we might want to use it to keep track of a list of users, employees, faculty, and so on.

It is not practical to utilise an object since it lacks methods for managing element order. We can't add a new property "between" the ones that already exist. Objects aren't designed to be used in this way.

To hold ordered collections, there is a particular data structure called Array.

There are three best ways to construct array in JS(JavaScript)

  • Creating an array using array literal
  • Creating instance of Array directly (using new keyword)
  • Using an Array constructor (using new keyword)
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating an array using array literal

In JavaScript, we can create an array using an array literal, which is a list of values enclosed in square brackets []. The values enclosed within the brackets are elements of an array which can hold any data type.

Syntax

let arrayName = [element1, element2, ...];

 

Here,

  • let: This keyword is used to declare a variable.
     
  • arrayName: It is the name of our array.
     
  • element1, element1: These are the elements of our array.

 

Example

  • JavaScript

JavaScript

// Initializing first array
let names = ["Smith", "Bob", "Mark", "Luke"];
console.log(names)

//Initializing second array
let marks = [70, 81, 93, 78];
console.log(marks)


Output

output

Explanation

In the above example, we initialized and displayed two array names and marks using array literals. The first array holds values of string types, while the other has values of type numbers.

Creating instance of Array directly (using new keyword)

In JavaScript, we can create an instance of an array directly using the new keyword followed by the Array constructor. The Array constructor is an in-built function using which we can create new arrays in JavaScript.

Syntax

let arrayInstance = new Array();

 

Here, 

  • arrayInstace: It is the name of our array variable.
     
  • new Array(): The new keyword creates a new instance of the Array() constructor. If no values are defined, then it will create an empty array.

 

Example

  • JavaScript

JavaScript

// Declaring the array
let student = new Array();

// Before initializing
console.log("Before initializing: ");
console.log(student);

student[0] = "Smith";  
student[1] = "John";  
student[2] = "David";

// After initializing
console.log("After initializing: ");
console.log(student);


Output

output

Explanation

In the above example, we created an instance of an array using the new keyword and the Array constructor, which will create an empty array for us. After that, we explicitly passed the array elements and printed them using the console.log() method.

Using an Array constructor (using new keyword)

In this method, we don't need to pass the array elements explicitly. Instead, we can pass them as arguments in the Array constructor itself.

Syntax

let arrayName = new Array(element1, element2, ...);

 

Here, 

  • arrayName: It is the name of our array variable.
     
  • new Array(): The new keyword is used to create a new instance of the Array constructor.
     
  • element1, element2: These are the elements of our array which are passed during array initialization.

 

Example

  • JavaScript

JavaScript

// Creating an array of number
let numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers);
console.log();

// Creating an array of strings
let names = new Array("Smith", 'Bob', 'David');
console.log(names);


Output

output

Explanation

In the above example, we created an array using the Array constructor and a new keyword by passing the arguments directly while declaring the array.

JavaScript Array Methods

Now, let us look at some JavaScript array method and their description.

Methods Description
every() It checks whether all array elements are satisfying the given condition.
flat() It creates a new array using the sub-array elements concatenated recursively till the specified depth is reached.
flatMap() It maps all the array elements and then flattens the result into a new array.
concat() It merges two or more arrays and returns a new array object.
copywithin() It copies the parts of the provided array with its own elements and returns the modified array.
entries() It creates a loop and an iterable object that iterates over every key-value pair.
fill() It fills elements in the array with static values.
filter() It returns a new array with elements that pass the given function condition.
from() It creates a new array with an exact copy of another array element.
find() It returns the value of the first element in the array that satisfies the given condition.
findIndex() It returns the index value of the first element in the array that satisfies the given condition.
includes() It checks for a specific element in the array.
forEach() It invokes the given function once for each element of an array.
indexOf() It searches for a specific element in the array and returns the index of the element with the first match.
isArray() It checks whether the value passed is an array or not.
join() It joins the array elements as a string.
lastIndexOf() It searches for a specific element in the array and returns the index of the element with the last match.
keys() It creates an iterable object with keys of the array and then loops through these keys.
map() It calls the specified function for each array element and returns the new array.
pop() It removes and returns the last array element.
push() It adds an element to the end of the array.
reverse() It reverses the array elements.
reduceRight() It runs the given function for each value from right to left, and finally, the array reduces to a single value.
shift() It removes the first element of the array and returns its value.
some() It checks whether any array element passes the test of the implemented function.
slice() It returns a new array with a copy of the part of the given array.
sort() It sorts and returns the array elements.
toString() It converts the array elements into string values without changing the original array.
values() It creates an iterator object with values of each array index.
unshift() It adds one or more elements at the beginning of the array.

Check out this problem - First And Last Occurrences Of X

Frequently Asked Questions

What is an array in JavaScript?

In JavaScript, an array is a fundamental data structure. An array is a special type of object that can store multiple values under a single variable. Unlike other languages, arrays in JavaScript can have values of different data types, such as numbers, strings, and objects.

How many types of arrays are there in JS?

In Javascript, arrays are divided into two types, one-dimensional arrays and multi-dimensional arrays. The one-dimensional or linear array consists of only one row or column. Meanwhile, a multi-dimensional array consists of one or more nested arrays.

What are two forms of array?

In Javascript, there are two forms of arrays literal arrays and constructed arrays. The literal arrays are created using the array literal enclosed within square brackets []. The constructed arrays are created using the new keyword and the Array constructor function.

Conclusion

In this article, we discussed the topic of Arrays in JS. We started by introducing arrays in general. Later on, we discussed declarations, functionalities, methods, loops, 2D arrays and what not to do in arrays.

We hope this blog has helped you enhance your knowledge of Arrays in JS. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

Previous article
Methods of primitive
Next article
Array Methods in Javascript
Live masterclass