Objects in JavaScript
Object Initializers
Here is how to create an object in the most common and simplest way:
const movie = {
imdbID: 'tt0082340',
title: 'Escape from New York',
frenchTitle: 'New-York 1997',
}
This is an object initializer: it is a collection of key-value pairs:
- this collection is enclosed by curly brackets
- the key is separated from the value by a colon
:
- each key-value pair is separated by a comma
,
By convention, each key-value pair is often placed on its own line, with no space before the colon and a space after it.
A key (the name of a property) can have any name. If a key has a name that is not a valid identifier*, it must be enclosed in quotes.
* to be brief, for an identifier to be valid, it must not contain spaces, punctuation marks, or special characters except $
and _
(it is actually a bit more complicated)
Syntaxes for Accessing an Object's Property
There are two different syntaxes for accessing an object's property.
Dot Syntax
const title = movie.title // dot syntax
Bracket Syntax
const imdbID = movie.imdbID // bracket syntax
In JavaScript, everything is a value, and any value can be stored in a variable.
'imdbID' // a value
const propName = 'imdbID' // The variable `propName` contains the value 'imdbID'
The bracket syntax allows retrieving the value of the property whose name is in a variable:
const prop = 'imdbID'
const imdbID = movie[prop]
Modifying an Object's Property
movie.title = 'Escape From New York'
Or (strongly discouraged if the property name is known):
movie.title = 'Escape From New York' // less readable, no completion in editors
// prone to (silent) errors, and less performant
Adding a Property to an Object
movie.brazilianTitle = 'Fuga de Nova York'
Or (discouraged, ditto):
movie.brazilianTitle = 'Fuga de Nova York'
Deleting a Property from an Object
Assigning the value undefined
to a property is not the same as deleting a property: in the first case, the property will still exist on the object.
To delete the property, there is the delete
operator which is used as follows:
delete movie.title
The bracket syntax is also valid here:
delete movie.title
Creating an Object with Dynamic Property Names
Since ES6, you can write this:
const propName = 'foo'
// ...later
const obj = {
[propName]: 'bar'
}
obj // { foo: 'bar' }
An Object is Only Equal to Itself
If two objects are created, and they contain the same properties with the same values, they are and remain two distinct values. Even if they are empty objects.
const one = {}
const two = {}
one === two // false
const sameOne = one // new name for the same value
sameOne === one // true
sameOne === two // false
const arr1 = []
const arr2 = []
arr1 === arr2 // false
const sameArr1 = arr1
sameArr1 === arr1 // true
sameArr1 === arr2 // false