JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print How to Print a Page Using JavaScript Textbox events in JavaScript How to find the largest number contained in a JavaScript Array?

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions JavaScript Beautifier Practice Javascript Online Object in JavaScript JavaScript Count HTML Interpreter Getters and Setters in JavaScript Throw New Error in JavaScript XOR in JavaScript Callbacks and Promises in JavaScript Atob in JavaScript Binary in JavaScript Palindrome Number in JavaScript How to Get First Character Of A String In JavaScript How to Get Image Data in JavaScript How to get URL in JavaScript JavaScript GroupBy Methods difference-between-var-let-and-const-keyword-in-java-script

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