JavaScript – Arrays

Array: Array can store more than one element but of same type

  • var arr = [10, 20, 30, 40, 50];
  • var marks = [56, 78, 34, 90, 67];

Memory Allocation:

  • All array elements store in consecutive memory locations.
  • We access element using their index.
  • Index starts with 0 to length-1

Display the elements of Array:

<html>
            <body>
                        <script>
                                    var arr = [10, 20, 30, 40, 50];
                                    document.write(arr[0] + ” <br/> “);
                                    document.write(arr[1] + ” <br/> “);
                                    document.write(arr[2] + ” <br/> “);
                                    document.write(arr[3] + ” <br/> “);
                                    document.write(arr[4] + ” <br/> “);
                        </script>
            </body>
</html>

Note:  It is recommended to use loops to process information of array

<html>
            <body>
                        <script>
                                    var arr = [10, 20, 30, 40, 50];
                                    document.write(“Array elements are : <br/>”);
                                    for (var i=0 ; i<5 ; i++){
                                                document.write(arr[i] + “<br/>”);
                                    }
                        </script>
            </body>
</html>

length: It is a pre-defined variable that returns the length of array

<html>
            <body>
                        <script>
                                    var arr = [10, 20, 30, 40, 50];
                                    document.write(“Array elements are : <br/>”);
                                    for (var i=0 ; i<arr.length ; i++){
                                                document.write(arr[i] + “<br/>”);
                                    }
                        </script>
            </body>
</html>

Program to display array elements in reverse order:

<!doctype html>
<html>
            <body>
                        <script>
                                    var arr = [10, 20, 30, 40, 50];
                                    document.write(“Reverse Array elements are : <br/>”);
                                    for (var i=arr.length-1 ; i>=0 ; i–){
                                                document.write(arr[i] + “<br/>”);
                                    }
                        </script>
            </body>
</html>
Scroll to Top