YogeshChauhan.com
2 Ways we can create an Array in JavaScript
December 17, 2020

Creating an Array using Literal

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:


var array_name = [item_1, item_2, item_3, ...];      

Examples


var cars = ["Audi", "Toyota", "Tesla"];
console.log(cars);

// [ 'Audi', 'Toyota', 'Tesla' ]

var cars = ["Audi", "Toyota", "Tesla"];
console.log(cars.length);

// 3

var cars = ["Audi", "Toyota", "Tesla"];
console.log(cars[0]);

// Audi

Creating an Array using new keyword

Syntax:


var array_name = new Array (item_1, item_2, item_3, ...);      

Examples


var cars = new Array("Audi", "Toyota", "Tesla");
console.log(cars);

// [ 'Audi', 'Toyota', 'Tesla' ]

var cars = new Array("Audi", "Toyota", "Tesla");
console.log(cars.length);

// 3

var cars = new Array("Audi", "Toyota", "Tesla");
console.log(cars[0]);

// Audi

Which one should you use to create arrays in JavaScript?

The two examples above do exactly the same. 

📌 For simplicity, readability and execution speed, use the literal way to create JS arrays.

Also, its behavior is predictable for any number of items.

Someone could easily overwrite the array if we use second method (not a realistic situation though):


function Array() { return []; }

alert(Array("Audi", "Toyota", "Tesla")); 

// it will show an empty alert box

Credit: MDN Docs

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

Flash of Invisible Text and Mitt Romney Web Font ProblemCSSModules and its Core features in JavaScriptJavaScriptJavaScript Number MethodsJavaScript3 Common Usability Mistakes In Web DesignUI/UXHow to enable GD library support for PHP on windows server?PHPHow to get query string values in JavaScript? (URL Manipulation using URLSearchParams)JavaScript