⬅ Go back to: Primitives and Reference Types

Working with Properties


Dot Notation

When working with dot notation, property identifies can only be alphanumeric (and _ and $). Properties can’t start with a number.

Dot notation is much easier to read than bracket notation and is therefor used more often.

(ie.) circle.location, circle.radius, circle.staticPropertyName

Bracket Notation

A second way to access properties on an object is called bracket notation.

When working with bracket notation, property identifiers only have to be a String. They can include any characters, including spaces. Variables may also be used as long as the variable resolves to a String.

This means there are fewer limitations when working with bracket notation. We can now have spaces in our strings, and can even start strings with numbers.

Perhaps most importantly, we can now use variables to access properties in an object. It’s important the variable you are using references a String.

(ie.) circle['location'], circle['center location'], circle['center-location'], circle[dynamicPropertyName]

If you have special characters or space on your property, you can use the bracket notation.


Adding / Removing Properties


    
    function Circle(radius) {
        this.radius = radius;
        this.draw = function() {
            console.log('draw');
        }
    }
    const circle = new  Circle(10);

    /**
     * Adding property
     */

        // An example using dot notation
        circle.location = { x: 1 };

        // An example using bracket notation
        const propertyName = 'center location';
        cirle[propertyName] = { x: 1 };

    /**
     * Removing property
     */

        // An example using dot notation
        delete circle.location;

        // An example using bracket notation
        delete circle['center location'];