Create a new Array JavaScript | Example code

  • by

Using an array literal is the easiest way to create a new Array in JavaScript. There is no need to use the new Array() way to create Array.

const array_name = [item1, item2, ...]; 

You can also create an array and then assign the elements.

const cars = [];
cars[0]= "AAA";
cars[1]= "BBB";
cars[2]= "CCC";

Create a new Array JavaScript

Simple example code Arrays can be created using the literal notation:

<!DOCTYPE html>
<html>
<body>

  <script>

    let fruits = ['Apple', 'Banana'];

    console.log(fruits.length); 
    console.log(fruits); 
  </script>

</body>
</html> 

Output:

Create a new Array JavaScript

Array constructor with multiple parameters

If more than one argument is passed to the constructor, a new Array with the given elements is created.

let fruits = new Array('Apple', 'Banana');

console.log(fruits.length); // 2
console.log(fruits[0]);     // "Apple"

Do comment if you have any doubts or suggestions on this JS array code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.