JavaScript arrays braces vs brackets

JavascriptArrays

Javascript Problem Overview


What is the difference between each of the following array definitions.

var myArray = [];
var myArray = {};
var myArray = new Array();

Javascript Solutions


Solution 1 - Javascript

The first and third are equivalent and create a new array. The second creates a new empty object, not an array.

var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array

Solution 2 - Javascript

var myObject = {}; is equivalent to var myObject = new Object();

So, the second example is not an Array but a general Object.

This can get confusing as Array is a class and Object is a class - more precisely Array is a sub-class of Object. So, by and large, Object semantics are applicable to an Array:

var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value';  // define a custom property.
console.log(o.property1);
console.log(o.length);  // Outputs '2' as we've only push()'ed two elements onto the Array

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPinkieView Question on Stackoverflow
Solution 1 - JavascriptjohusmanView Answer on Stackoverflow
Solution 2 - JavascriptleepowersView Answer on Stackoverflow