×

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

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

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

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 radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes 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 Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

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

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.

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