In this guide, we will also show you how to dynamically set a new property.
Take a look at the following object:
What if we wanted to add a new object property representing that person’s hometown?
//Setting a new property using dot syntax. person.hometown = 'Wilmington, North Carolina';
In the snippet above, we used dot notation to set a new property called “hometown”.
Dot notation can also be used to overwrite an existing property. For example, if we wanted to change the name of the person, we could do something like this:
//Overwriting an object property. person.name = 'LeBron James';
Here, we were able to overwrite the value of the name property.
In certain cases, you might not be able to manually specify the property name like we did in the examples above.
Thankfully, there is an easy way around this:
//Dynamically setting properties var propertyName = 'new_property'; //Use square brackets person[propertyName] = 'Test';
In other words, it will take it literally.
Using spaces or hyphens in a property name.
If you attempt to use a space or a hyphen in your property name while using regular dot notation, you might end up with an error such as:
Uncaught SyntaxError: Invalid left-hand side in assignment
The error above occurred because I tried to use a hyphen like so:
//This will cause a SyntaxError person.name-test = 'LeBron James';
If you attempt to use a space in the property name, you will probably get the following error:
Uncaught SyntaxError: Unexpected identifier
In order to use spaces or hyphens in your object property names, you must use the square bracket approach:
//Using a space in a property name. person["name test"] = 'LeBron James';
By wrapping my new property name in quotes and square brackets, we were able to use a space character.