Learning web technologies one class at a time

JavaScript Tip: Adding Property to an Object

After you’ve declared your object, however, you can still add key/value pairs to it in a couple of ways.

1

2

3

4

varobj={};

obj["firstName"]="Hugo";

obj["lastName"]="Reyes";

This is known as bracket notation. The alternative and more common syntax is dot notation. Here’s an example:

JavaScript

1

2

3

4

varobj={};

obj.firstName="Hugo";

obj.lastName="Reyes";

Dot notation is simpler than bracket notation; however, there are certain tasks that can only be done with bracket notation. For example, you can use a variable inside the brackets, which can’t be done using dot notation. Bracket notation also supports strings containing spaces and other characters that are invalid in dot notation.