Basic Introduction To Array In JavaScript

avatar


image.png

Image Source

Array is one of the major datatype in JavaScript that is used to store a particular data in an order. Instead of creating multiple variables to store a data, you can use array to store many data of particular type in a single variable. In JavaScript, arrays are created using the square brackets ([]). The value written inside the square brackets and separated by comma is called the element and there is a particular term that is used to identify the position of certain value which is called index. And array always starts from index 0. Like C programming language, you don't have to define the size of array. It can allocate the size as per your prgram need. That's why arrays in JS are considered to be dynamic.

Another cool feature within JavaScript array is that you can store value of any particular datatype like string, number, boolean and so on. A common example would be: const arr1 = ["BMW", 23, true]. You can do more than this. You can mix them with another array inside this array or even with objects. This is also one way of declaring an array. Another way to declare an array is by using constructor called Array(). A simple example is:

const arr2 = new Array("Spinach", "Brinjal", "Cabbage");

The first notion we discussed above is known as creating array by array literal and is always recommended while dealing with array. The second one i.e. the use of new keyword and using constructor Array() is not so recommended as it tends to slow your program due to use of constructor.

For now we will just write a simple loop that iterates over the array value and show the output and will discuss about other stuff with Array in the coming next post.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Array</title>
<script>
    const arr1 = [2, 3, 4, 5];
    const arr2 = new Array("Spinach", "Brinjal", "Cabbage");
    for (var i=0; i<arr1.length; i++)
    {
        document.write("<h3>" + arr1[i] + "</h3>")
    }

    for (var i=0; i<arr2.length; i++)
    {
        document.write("<h3>" + arr2[i] + "</h3>")
    }
</script>
</head>
<body>
</body>
</html>

You can see the output as below in the browser screen:

image.png



0
0
0.000
2 comments
avatar

Thank you, useful information,🙏🙏

0
0
0.000