Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript arrays braces vs brackets

People also ask

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

Whats the difference between {} and [] in array?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What is the difference between {} and []?

The difference between “{}” and “[]” is that {} is an empty array while [] is a JavaScript array, but there are more! In JavaScript, almost “everything” is an object. All JavaScript values, except primitives, are objects.

What does brackets mean in arrays?

now in your case you have an array of array's so the first(or outside) curly brackets are for defining each row and the curly brackets within them is to define each row's values inside them.


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

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