Traverse array object using JavaScript

JavaScript lacks a dedicated built-in function specifically designed for iterating through the elements or objects within an array. You can easily traverse an array utilizing a for loop or by accessing elements directly through their index. An array consists of several elements of a uniform type, and these can be navigated using a for loop.

In this section, we will explore various techniques for navigating through an array:

Simple Array traversing

In this illustration, we will directly navigate through an array using the array's index.

Copy Code

Example

<script>

// declare and initialize an array

var message = ["Have", " a", " good", " day"]; 



//traverse the array elements

document.write("array[0] = " + message[0]);

document.write("<br> array[1] = " + message[1]);

document.write("<br> array[2] = " + message[2]);

document.write("<br> array[3] = " + message[3]);

</script>

Output

Store the code and execute it in your web browser. The array will iterate through its elements and display them.

Example

array[0] = Have 

array[1] = a 

array[2] = good 

array[3] = day

Screenshot

Traverse and display Array elements

In this illustration, we will directly navigate through an array by utilizing the array index and present the string contained within the array.

Copy Code

Example

<script>

// declare and initialize an array

var message = ["Have", " a", " good", " day"]; 



//traverse the array elements

document.write(message[0]);

document.write(message[1]);

document.write(message[2]);

document.write(message[3]);

</script>

Output

Store the code and execute it in your web browser. The array will iterate through its elements and display them.

Example

Have a good day

Screenshot

In addition to this, JavaScript provides several alternative techniques for iterating through an array. In this discussion, we will focus on the most commonly used and straightforward approach.

Traverse array using for loop

The previously mentioned approach tends to be inefficient when dealing with large arrays or when there are numerous variables involved. Therefore, it is necessary to explore alternative methods for traversing an array in order to optimize both time and effort.

To address this issue, the notion of loops has been introduced, allowing for efficient traversal of an array with minimal code. We will now explore various types of loops to iterate through the elements of the array and present them on the web. You have the option to utilize a while loop, a do-while loop, a for loop, or a for-each loop to navigate through an array. This approach is comparable to other programming languages such as C, C++, and Java.

Example 1

Here is an illustration of navigating through an array with the use of a for loop while outputting the string components of the array.

Copy Code

Example

<script>

// declare and initialize an array

var message = ["Die", " with", " memories,", " not", " dreams"]; 



//traverse the array and print the elements

for(var i=0; i< message.length; i++){

document.write(message[i]);

}

</script>

Output

Store the code and execute it in the browser. The array will iterate through its elements and display them.

Example

Die with memories, not dreams

Screenshot

Refer to the web screenshot for the JavaScript code mentioned above:

Example 2

Here is an illustration of how to iterate through an array utilizing a for loop to display the integer values contained within this array.

Copy Code

Example

<script>

// declare and initialize an array with integer values

var integerArray = [34, 67, 12, 89, 45, 79]; 



//traverse the array using for loop 

for(var i=0; i< integerArray.length; i++) {

       //display the array elements

      document.write(integerArray[i] + "<br>");

}

</script>

Output

Store the code and execute it in your web browser. The array will iterate through its elements and display them.

Example

34

67

12

89

45

79

Screenshot

Please refer to the webpage screenshot corresponding to the JavaScript code mentioned above:

Example 3: Traverse using while loop

In this illustration, we will implement a while loop to iterate through an array and subsequently present the elements contained within this array.

Copy Code

Example

<script>

// declare and initialize an array with integer values

var integerArray = [34, 67, 12, 89, 45, 79]; 

var i=0;



document.write("Elements in array: <br>");

//traverse the array using while loop

while( i< integerArray.length) {

   //display the array elements

   document.write(integerArray[i] + "<br>");

   i++;

}

</script>

Output

Store the code and execute it in your web browser. The array will iterate through its elements and display them.

Example

Elements in array:

34

67

12

89

45

79

Screenshot

Refer to the web screenshot corresponding to the aforementioned JavaScript code:

Traverse array using forEach method

In addition to the fundamental loops such as for, while, and do-while loops, JavaScript offers another looping mechanism, which can also be described as an array method known as forEach. This method distinguishes itself from the basic loops by invoking a function for every individual element contained within an array.

Syntax

The syntax for the forEach method is also distinct; consider the following structure of the forEach method:

Example

arr.forEach(functionName);

Example

This example illustrates the functionality of the forEach method when applied to array elements. Initially, the array, combined with the forEach method, will invoke a user-defined function. Subsequently, this function will iterate through all the elements of the array and present them on the web page. Refer to the code provided below:

Copy Code

Example

<script>

// declare an array and provide value in it 

var message = ["It", " is", " very", " beautiful", " day"]; 

var index = 0;



//call the user-defined function with array

message.forEach(traverseArray);



//definition of user-defined function

function traverseArray(ele, index)

{

    //display the array elements using index 

    document.write(ele);

}

</script>

Output

Store the code and run it in your browser to display all the elements of the array on the webpage. Refer to the response below:

Example

It is very beautiful day

Screenshot

Refer to the web screenshot corresponding to the JavaScript code mentioned above:

Traverse an array using every method

This approach differs from traditional loops and the forEach method. Essentially, it is employed to iterate through an array while adhering to certain conditions defined by the developer. The every method is a JavaScript function designed to evaluate the given condition against every element within the array.

It yields true if every element meets the specified condition and successfully passes the provided test function. If this is not the case, it returns false.

Syntax

Here is the syntax for every method:

Example

arr.every(condition);

Example 1

In this illustration, we will iterate through the entire array to assess whether the specified values meet the condition of being greater than 18, thereby determining if all individuals are considered adults. Please refer to the code provided below:

Copy Code

Example

<script> 

//define an array with elements

var age = [22, 28, 36, 26, 34, 31];

  

//put a condition to check all the values are greater then 18

const adult = x => x > 18; 

  

if (age.every(adult)) { 

    //display the message if all array values are > 18

    document.write('All are adults'); 

} 

else { 

    //display the message if any one of them is less than 18

    document.write('Atleast one is not adult'); 

} 

</script>

Output

Store the code and run it in your web browser. If every value in the array is greater than 18, it will present the message “All are adults.” Conversely, if at least one value is 18 or below, it will show “At least one is not adult.” Refer to the response below:

Example

Atleast one is not adult

Screenshot

Refer to the web screenshot corresponding to the aforementioned JavaScript code:

Example 2

In this illustration, we will iterate through the entire array to verify whether all the specified values within the array are even numbers. To accomplish this, we will implement a conditional check (even = x => x % 2 === 0). This will yield a true result if all numbers are indeed even; otherwise, it will produce a false result. Below is the code for your reference:

Copy Code

Example

<script> 

//define an array with elements

var age = [12, 47, 16, 26, 34, 59];

  

//put a condition to check all the values are greater than 18

const adult = x => x > 18; 

  

if (age.every(adult)) { 

    //display the message if all array values are > 18

    document.write('All are adults'); 

} 

else { 

    //display the message if any one of them is less than 18

    document.write('Atleast one is not adult'); 

} 

</script>

Output

Store the code and run it in the browser; it will display the message "All are even numbers" if every element in the array is greater than 18. Conversely, it will show "At least one of them is not an even number." Refer to the response below:

Example

Atleast of them is not an even number

Screenshot

Refer to the web screenshot corresponding to the JavaScript code mentioned above:

Traverse an array using map

In JavaScript, the map function serves as a technique that executes a specified function on each element of an array, subsequently generating a new array as a result. This process allows for a complete traversal of the original array.

The map function allows you to execute operations on the elements of an array as you iterate through it. Essentially, it goes through the entire array to carry out specific operations on each individual element within that array.

Syntax

The following illustrates the syntax of the map function in JavaScript:

Example

arr.map(condition);

It returns a newly created array.

Look at the below examples how map is used:

Example 1

In this instance, we will iterate through the entire array by utilizing the map function available in JavaScript to execute the Math.sqrt operation on each element of the array. Observe the implementation using JavaScript methods:

Copy Code

Example

<h3> Perfrom sqrt on each element of array using map() </h3>

<script>

//initialize an array with value

var numbers1= [4, 16, 36, 64, 100, 144, 196, 256, 324, 400];



//call the user-defined function using map

var numbers2 = numbers1.map(myFunction);



//display the array elements before and after performing sqrt operation

document.write("Inital array elements: " + numbers1);

document.write("<br> <br>");

document.write("Array after sqrt: " + numbers2);



//function definition where perform sqrt on each element of array

function myFunction(value, index, array) {

  return Math.sqrt(value);

}

</script>

Output

Store the code and run it in your browser, which will display all the elements of the array both prior to and following the execution of the sqrt operation. In this context, the map function will facilitate the iteration over each element within the array.

Refer to the web screenshot corresponding to the JavaScript code mentioned above:

Example 2

Additionally, you can execute basic arithmetic operations utilizing the map function. Refer to the example code provided below:

Copy Code

Example

<h3> Perfrom addition on each element of array using map() </h3>

<script>

//initialize an array with value

var numberArray = [5, 9, 8, 2, 6];



//call the user-defined function using map

var numbers2 = numberArray.map(myFunction);



//display the array elements before and after performing operation

document.write("Inital array elements: " + numberArray);

document.write("<br><br>");

document.write("<b> Add 10 to each element of the array </b><br>");

document.write("Newly created array: " + numbers2);



//function definition where perform simple addition on each element of array

function myFunction(ele, index, array) {

  return ele + 10; 

}

</script>

Output

Examine the web output generated by the code provided above. It will display all elements of the array with an additional 10 added to each of them.

Input Required

This code uses input(). Please provide values below: