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:
Print the array on the console:
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:
Print the object on the console using “console.log()” method:
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.