JavaScript Arrays: The Difference Between [] and {}
Table of Contents
In this post, we'll learn about the difference between []
and {}
in JavaScript arrays.
Specifically, we'll learn about the difference between the two following examples:
JAVASCRIPTconst fruits = ["apple", "banana", "orange"];
JAVASCRIPTconst fruits = {
0: "apple",
1: "banana",
2: "orange"
};
What is an array?
Before we get into the details, let's first understand what an array is.
An array is a collection of data that is ordered and can be accessed by a numerical index.
Because JavaScript is flexible, an array can contain any type of data, including numbers, strings, objects, and even functions.
Square Brackets []
In JavaScript, you can use square brackets to create an array. The following is an example of an array:
JAVASCRIPTconst array = ["apple", "banana", "orange"];
Because it is an array, you can call the length
property on it to get the number of items in the array.
JAVASCRIPTconst array = ["apple", "banana", "orange"];
console.log(array.length); // 3
Another way to create an array is to use the Array()
constructor.
JAVASCRIPTconst array = new Array("apple", "banana", "orange");
In all three cases, you'll have an array.
Curly Braces
Curly braces in JavaScript are used to create an object, not an array. Let's look at our earlier example:
JAVASCRIPTconst fruits = {
0: "apple",
1: "banana",
2: "orange"
};
This is an object, where the keys are the numerical indices and the values are the strings.
Because it's an object and not an array, you cannot call the length
property on it.
JAVASCRIPTconst fruits = {
0: "apple",
1: "banana",
2: "orange"
};
console.log(fruits.length); // undefined
It returns undefined
because objects don't have a length
property.
Conclusion
So to summarize the difference, the difference between []
and {}
is that []
is an array and {}
is an object.
Each one is different and so have different properties and behaviors. Make sure to use the right one despite their similar syntax!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript