We’ve already seen some special objects built into JavaScript, such as the Wrapper objects (Number
, String
, Boolean
), Math
, and BigInt
objects. There are also Date
and RegExp
, and others.
Although these objects look like objects in Java/C++, the true nature of objects in JavaScript is far from objects in Object-Oriented programming! Instead, JavaScript objects are more similar to Dictionaries in Python (or HashMap in Java, Hash Tables in C++).
JavaScript objects are, in a nutshell, a collection of key-value pairs.
Each key-value pair is called a “property.”
You can access property value with dot notation or square bracket notation:
You can modify property value the same way:
You can even add new properties the same way:
And, you can remove properties:
Accessing a nonexistent property yields undefined
.
You can create an empty object and then add properties to it:
Note that you can make an empty object using object constructor syntax as follows:
But it is more common to use the object literal syntax instead:
We can use square brackets in an object literal when creating an object. That’s called computed properties.
A common pattern you might encounter is using a variable to automatically create a key-value pair as in the example below:
If a variable is used as above, a key-value pair is created where the key is the variable’s name, and the value is the variable’s value. It is same as:
Convenient syntax for fetching multiple elements:
You can rename the properties
You can even do this:
JSON (JavaScript object notation) is a standard text-based format for representing structured data based on JavaScript object syntax. It was popularized by Douglas Crockford. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client so that it can be displayed on a web page, or vice versa).
JSON closely resembles JavaScript object literal syntax except:
true
, false
, null
, arrays, and objects.undefined
values not allowed.There is a special built-in JSON
object that contains methods for parsing JSON and converting values to JSON. For a reference, visit the documentation on MDN website.