JavaScript – Create Array

To create an array in JavaScript, we can use square-bracket notation [], or Array() constructor.

In this tutorial, we will learn how to crate an array in JavaScript, with examples.

Create Array using Square-bracket Notation

To create an array using square-bracket notation, specify the elements as comma separated values, and enclose them in opening and ending square brackets.

</>
Copy
[element1, element2, element3, element4]

In the following example, we create an array with three elements.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = ['apple', 'banana', 'cherry'];
        document.getElementById('output').innerHTML = 'Array : ' + arr;
    </script>
</body>
</html>

Create Array using Array() Constructor

To create an array using Array() constructor, call the constructor() and pass the elements as arguments to this constructor.

</>
Copy
Array(element1, element2, element3, element4)

The constructor creates and returns an Array object with the specified elements.

In the following example, we create an array with three elements.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = Array('apple', 'banana', 'cherry');
        document.getElementById('output').innerHTML = 'Array : ' + arr;
    </script>
</body>
</html>

Create Array of Specific Size

We can also create an Array of specific size, without specifying the elements of Array.

To create an array of specific size, pass the size as argument to Array() constructor.

</>
Copy
Array(size)

In the following example, we create an array of size 5.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var arr = Array(5);
        document.getElementById('output').innerHTML = 'Array : ' + arr;
    </script>
</body>

Conclusion

In this JavaScript Tutorial, we learned how to create an Array in JavaScript, with examples.