×

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable.

What is an Array in JavaScript?

The array is a special kind of variable that can hold the group of values at a time.We can also say that it stores the data in the form of an ordered list.

The array of JavaScript has some distinct properties unlike the arrays of other programming languages such as c / c ++.

  • JavaScript's array has the ability to store data of different data-types in each slot/cell. For example- it can be in the form of strings, objects, integer numbers, etc.
  • The length of JavaScript's arrays is dynamic and grows automatically according to requirements.

 Common characteristics of Arrays are as follows:

  • The values stored in an array are known as elements.
  • Each element of an array has its own specific numeric position, which is known as an index.

To understand the concept of Array let’s see an example:

Why we need Arrays

Suppose you want to store the name of colors in your JavaScript code. Storing color names one by one in a variable might look like this:

var colorx="Red";
var colory="Green";
var colorz="Blue";

As we can see this is an easy task, but in scenarios, where you have to store huge data such as student's records, it is impossible to create separate variables for each student's record and it is not a good idea either. So arrays are used to solve such problemsas by creating an array you can store any number of elements or student records under any specific variable.

Creating an Array in JavaScript

The following given syntax is the easiest way of creating an array in JavaScript.

var my1StArray = [element0, element1,element2 ..., elementN];

let see another example:

var colors = ['red', 'green', 'blue'];

There is also another way to create an array in JavaScript, in which you can use the Array () constructor to create an array as shown below:

var myArray = new Array(element0, element1, element2 ..., elementN);

let’s see more examples

var athletes = new Array(3); // creates an array with initial size of  3

var scores = new Array(1, 2, 3,4); // creates an array with four numbers 1,2, 3,4

var signs = new Array('Orange'); // creates an array with one element 'Orange'

How to create arrays in JavaScript. Let us understand this in more detail through an example:

Example

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Arrays in JavaScript</title>
</head>
<body>
<script>
    // Creating variables
var cars   = ["Saab","Volvo","BMW"];
var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["Erik", "Doe", 24];
    // Printing variable values
document.write(cars + "<br>");
document.write(colors + "<br>");
document.write(fruits + "<br>");
document.write(cities + "<br>");
document.write(person);
</script>
</body>
</html>

In the above given program, we have created many variables like car, fruit, city, person, etc., and in each variable we have stored many related data/records.

Output

JavaScript Arrays

These are some of the basic operations that are usually performed on arrays.

  1. Accessing  the  Elements of an Array:

To access any element of an array, first you need to understand the concept of indexing. An index is a numerical value that refers to the position of an element in an array. Each element of an array has a specific numeric position or index value. In most of the programming languages, the arrays are zero-based, which means the first element of the array is stored at (0) index, the second element at (1), and so on.

The user can use the index value to access any element of the array.

For example

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
fruits=[0] represents the element  (Apple)
fruits=[1] represents the element  (Banana)
fruits=[2] represents the element  (Mango)

 Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Accessing individual Elements of an Array</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write("fruits[0]=" +fruits[0] + "<br>"); // Prints: Apple
document.write("fruits[1]=" +fruits[1] + "<br>"); // Prints: Banana
document.write("fruits[2]=" + fruits[2] + "<br>"); // Prints: Mango
</script>
</body>
</html>

Output

JavaScript Arrays
  • Finding Length of an Array

The length of an array refers to the total number of elements present in the array. You can find the length of an array by using the "length” property. Furthermore,remember one thing that the length of an array is always greater than the index value of any element present in the array.

Syntax

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

vartotalElements=fruits.length;// The length property returns the total number of elements of array

document.write(totalElements);

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Finding the length of an Array</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
vartotalElements=fruits.length;
document.write("Total Numbers of Elements Presents in array are =" +totalElements + "<br>"); //Output will be 5
document.write(fruits.length );// Another way
</script>
</body>
</html>

In this program, the length property is used to find the length of the array.

Output

JavaScript Arrays
  • Traversing all elements of the array by using the "for" loop:

User can access/traverse all elements of an array with the help of "for" loop:

For Example:

var cars =["Saab","volvo","BMW"];// Iterates over array elementsfor(vari=0;i<cars.length;i++)
{
document.write(cars[i]+"<br>");
}// Print array element

Programs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Loop Through an Array Using For Loop</title>
</head>
<body>
<script>
var cars = ["Saab", "volvo", "BMW"]; // Iterates over array elements
for(vari = 0; i<cars.length; i++)
{
document.write(cars[i] + "<br>");
} // Print array element
</script>
</body>
</html>

In the above program, we have used the “for” loop statement to traverse each element of the array. In the “for” loop, we have also used the “length” property to get the total number of elements present in the array.

Output

JavaScript Arrays

In JavaScript 6, a new and easier way to iterate over elements of an array is now available, which is known as “for of “ loop statement.

Syntax of the “for of” statement:

var cars = ["Saab", "Volvo", "BMW"]; // Iterates over array elements
    for(var car of cars)
{   
        document.write(car + "<br>"); // Print array element
    }

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>For-Of Loop</title>
</head>
<body>
    <script>
    var cars = ["Saab", "Volvo", "BMW"]; // Iterates over array elements
    for(var car of cars){   
        document.write(car + "<br>"); // Print array element
    }
    </script>
</body>
</html>                            

In the above program, we have used the "for" loop statement to print the elements of the array.

Output

JavaScript Arrays
  • Adding  elements to the array:

To add new elements to an array, the easiest way is to use the "push ()" function.

Syntax

var cars = ["Saab","Volvo", "BMW"];
cars.push("Nissan");    // adding a new element (Lemon) to fruits

Program

<!DOCTYPE html>
<html>
<body>
<p>Here we used push method to add a new element to an array.</p>
<script>
  var cars = ["Saab", "Volvo", "BMW"]; // Iterates over array elements
document.write("Elements of array"+"<br>");
for(var car of cars){  
        document.write(car + "<br>");
    }
document.write("Elements of array affter adding new element" +"<br>");
cars.push("Nissan");
    for(var car of cars){   
        document.write(car + "<br>");
    }
</script>
</body>
</html>

In the above program, we have used the "push ()" function to add a new element to our array. The "push ()" function is one of JavaScript's predefined functions.

Output

JavaScript Arrays

Related Topics

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.