ADVERTISEMENT

Difference Between [] and {} – JavaScript

JavaScript
ADVERTISEMENT

Conceptually everything in JavaScript is an object, which means that it has properties and methods. Few examples of objects are variables, lists, and arrays, etc. However, there are few exceptions to that, for example, undefined

We can use “Developer console” or “Developer Tools” in Mozilla Firefox or Google Chrome more conveniently to print out any object or array and study the details.

You can also use an object.getOwnPropertyNames() to list all the property names of objects or use object.hasOwnProperty(“property name”) to see whether a specific property is available or not.

So, what is the meaning of {} in JavaScript?

In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis 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.

var obj_name = {};
JavaScript Object Declaration {}

What is the meaning of [] in JavaScript?

We use [] brackets for creating an empty array which is a data structure used to store a collection of values. This is similar to an object, but it is a unique data structure to hold more than one values at a time.

var array_name = [];
JavaScript Object Array Declaration using [] brackets

If we compare the output shown in Developer Console for both {} and [] declaration of variables, we can easily spot the difference i.e.

So, in short, you can use {} braces to declare a single object whereas use [] brackets to create an array/list of items.

JavaScript Object and Array Difference

The following JavaScript code demonstrates the use of Brackets [] and Braces {} to create an array or object.

// Array
const arr = [1, 2, 3];

// Object
const obj = { name: 'John', age: 30 };

A similar concept is used in JSON to declare objects or arrays such as:  

{"name":"Smith", "gender":"male", "location":"CA"}

Will create an object; however, the following will create an array of items.

[{"name":"Smith", "gender":"male", "location":"CA"}]

You can use any of the braces {} or brackets [] to declare an empty array. However, it’s your choice to use square brackets with JavaScript objects.

References:

ADVERTISEMENT
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post