JavaScript

What’s the Difference Between “{}” and “[]” While Declaring a JavaScript Array

Understanding the difference between square brackets and curly braces in JavaScript is important for working with arrays and objects effectively. Although both data structures can hold collections of data, there are various differences between them. Arrays are ordered lists of values, while objects consist of key-value pairs. In JavaScript, the syntax for declaring arrays and objects is slightly different. Arrays are declared with square brackets [ ], while objects are declared using curly braces { }.

This blog will explain the difference between curly braces and square brackets in JavaScript while declaring an array.

What’s the Difference Between “{ }” and “[ ]” While Declaring a JavaScript Array?

In JavaScript, curly braces { } are used for declaring objects while square brackets [ ] can be used to declare an array. The elements inside the square brackets are separated by commas.

Let’s see examples to create an array and object using the { } and [ ].

Example 1: Declare an Array Using “[ ]” and “{ }”

Create an array named “lang” that stores programming languages:

var lang = ['HTML','CSS','JavaScript','Node.js','react.js'];

Print the array on the console:

console.log(lang);

Output

Now, try to declare an array using curly brackets, it will give “SyntaxError”:

Curly braces {} are usually used to declare objects, which are a type of data structure that can store a collection of key-value pairs.

Example 2: Declare an Object Using “{ }” and “[ ]”

Create an object named “stdInfo” that stores the student information in key-value pairs:

const stdInfo = {id: 1, name: "Stephen", age: 18};

Print the object on the console using “console.log()” method:

console.log(stdInfo);

Output

If we will try to store key-value pairs in [ ] notation, it will give an error:

It’s worth noting that you can use an object to simulate an array-like data structure in JavaScript, but it is not a true array, and may not have all the same methods and properties as an actual array.

Conclusion

The curly braces { } are used for declaring objects while square brackets [ ] can be utilized to declare an array. The [ ] is the standard way to declare an array in JavaScript and is commonly used while the { } is used to declare objects, which are similar to arrays but have some differences. Objects are a collection/group of key-value pairs, while arrays are a collection of ordered values. This blog explained the difference between curly braces and square brackets in JavaScript while declaring an array.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.