Objects in JavaScript are used to store collections of data in the format of âkey: valueâ pairs. Contained within an object we can have any number of variables and/or functions which are then referred to as object properties and methods.
Creating an Object
Letâs work with an example! To initialize a variable car as an object**,** we use curly braces {}:
var car = {};
We now have an empty object which can be accessed via the Developer Tools console, by simply typing our variable name:
car
// {} [object]
An empty object isnât all that useful, so let's update it with some data:
var car = {
name: 'Tesla',
model: 'Model 3',
weight: 1700,
extras: ['heated seats', 'wood decor', 'tinted glass'],
details: function() {
alert('This ' + this.name + ' is a ' + this.model + ' it weighs ' + this.weight + 'kg and includes the following extras: ' + this.extras[0] + ', ' + this.extras[1] + ' and ' + this.extras[2] + '.');
},
display: function() {
alert('This car is a ' + this.name + '.');
}
};
Letâs access this data in our developer tools console:
car.name // Tesla
car.model // Model 3
car.weight // 1700
car.extras[1] // wood decor
car.details() // This Tesla is a Model 3 it weighs 1700kg and includes the following extras: heated seats, wood decor and tinted glass.
car.display() // This car is a Tesla.
As you can see, each name/value pair must be separated by a comma, and the name and value in each case are separated by a colon. The syntax will always follow this pattern:
var objectName = {
member1Name: member1Value,
member2Name: member2Value,
member3Name: member3Value
};
The value of an object member can be pretty much anything â in our car object, we have two strings, a number, an array, and two functions. The first four items are data items and are referred to as the objectâs properties. The last two items are functions that allow the object to do something with that data and are referred to as the objectâs methods.
This kind of object is called an object literal â weâve literally written out the object contents as weâve created it. This is in comparison to objects instantiated from classes, which weâll take a look at later on.
Dot notation
Above, youâve seen the objectâs properties and methods accessed using dot notation. The object name car
 acts as the namespace â it needs to be entered first to access anything within the object. Then you write a dot, followed by the item you want to access â this can be the name of a simple property, an item of an array property, or a call to one of the objectâs methods, for example:
car.name
car.extras[1]
car.details()
Deleting Properties
We can use the delete operator to remove properties, like so:
car.model
// Tesla 3
delete car.model
car.model
// undefined
Square Brackets
If for example, we had a multi-word property within our object, such as:
var user = {
name: "Sam",
age: 32,
"likes potatoes": true // a multiword property name must be quoted
};
We couldnât access the multi-word property with dot-notation:
user.likes potatoes // syntax error!
This is because a dot requires the key to be a valid variable identifier. That is no spaces and other limitations.
The alternative is to use square brackets, which works with any string:
let user = {};
// set
user["likes potatoes"] = true;
// get
alert(user["likes potatoes"]); // true
// delete
delete user["likes potatoes"];
Updating object members
We can update the values within our objects by simply declaring the property youâd like to set with the new value, like so:
user.age // 32
user.age = 33 // 33
user.age // 33
You can also create completely new members of your object. For example:
user.surname = 'Smithessson';
// user
{name: "Sam", age: 33, likes potatoes: true, surname: "Smithessson"}
What is âthisâ?
You may have noticed the use of the word âthisâ in our earlier example. See the following:
display: function() {
alert('This car is a ' + this.name + '.');
}
The this
 keyword refers to the current object that the code is being written inside ofâ so in this case this
 is equivalent to car
.
Why not just write car
 instead? Itâs best practice to write well-constructed object-orientated code, and in doing so the use of this
 is extremely useful. It will ensure the correct values are used when a member's context changes (e.g. two different car
 object instances may have different names, but will want to use their own name when displaying their own information).
For example:
var car1 = {
name: 'Tesla',
display: function() {
alert('This car is a ' + this.name + '.');
}
}
var car2 = {
name: 'Toyota',
display: function() {
alert('This car is a ' + this.name + '.');
}
}
In this case, car1.display()
 will output "This car is a Tesla." And car2.display()
 will output "This car is a Toyota.", even though the method's code is exactly the same in both cases.
As this
 is equal to the object the code is inside âthis
 becomes really useful when you are dynamically generating objects (for example using constructors), which is outside the scope of this article!
Conclusion
And thatâs it! You should now have a good idea of how to work with objects in JavaScript â including creating your own simple objects, as well as accessing and manipulating object properties. Youâll also begin to see how objects are very useful as structures for storing related data and functionality.
For instance, if you tried to keep track of all the properties and methods in our car
 object as separate variables and functions, it would be extremely inefficient, and we'd run the risk of clashing with other variables and functions that have the same names. Objects let us keep the information safely locked away in their own package.
Related Posts:
A little about me..
Hey, Iâm Tim! đ
Iâm a developer, tech writer & author. If youâd like to see all of my articles, you're in the right place! Browse the blog categories to find what interests you.
Iâm currently working on building my Complete Guide to Freelancing. The bad news is that itâs not available yet! But if itâs something you might be interested in, you can sign up to be notified when itâs available đ
Thanks for reading!