×

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

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

6 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

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.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 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.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute 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.

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.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute 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.