Dot vs Bracket Notation
In this lecture, we will learn how to reference data from an object and change data in objects using both the dot and bracket notation.
Let's consider our user
object from the previous lecture.
const user = {
firstName: 'John',
lastName: 'Doe',
job: 'Software Engineer',
age: 32,
fruits: ['Banana', 'Apple', 'Melon'],
friends: ['Eric', 'Ulrich', 'Mary'],
};
Using the dot (.)
notation is very straightforward. Let's say we want to get the job property:
console.log(user.job); // Result ==> Software Engineer
The dot notation is an operator that will go to the user
object and then retrieve the property with the specified name. In our case, the job
property.
We can do the same thing using the bracket notation.
console.log(user['job']); // Result ==> Software Engineer
The big difference between these two methods is that we can put any expression that we'd like in the bracket notation. We don't have to explicitly write the string inside the brackets; instead, we can compute it from some operation. Remember that an operation is an expression .ie. something that produces a value.
const key = 'Name';
console.log(user['first' + key]); // Result ==> John
console.log(user['last' + key]); // Result ==> Doe
You cannot use this method with the dot notation because with the dot notation; you must use the real property name and not a computed property name.
Before moving forward, I want to let you know that you will get undefined
if you try to get a property that does not exist in an object.
To finish, now that we know how to retrieve elements from an object, let's learn how to use both the dot and bracket notation to add new properties to an object.
user.location = 'Paris';
user['twitter'] = '@constjavascript';
console.log(user); // user object with the properties location and twitter added to it