Yogesh Chauhan's Blog

2 Ways we can create an Array in JavaScript

in JavaScript on 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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to define constants in PHP?PHPFive common features of Angular template syntax (with examples)AngularUnderstand Inheritance in PHP in this Basic Example (For Beginners)PHPList of social media icon logo color codes in HEXMiscellaneousWhat are Web services?MiscellaneousModules and its Core features in JavaScriptJavaScript