DEV Community

Cover image for Property accessors

Property accessors

Understanding Property Accessors in JavaScript

In JavaScript, property accessors are mechanisms that allow you to access the properties of an object. There are two primary ways to do this: dot notation and bracket notation.

Dot Notation

Dot notation is the most common way to access properties. You simply use a dot (.) followed by the property name.

Bracket Notation

Bracket notation is useful when the property name is dynamic or not a valid identifier (e.g., it contains spaces or special characters). You use square brackets ([]) and pass the property name as a string

Creating objects in JavaScript

The language provides syntax known as object literal notation for quickly creating objects. Object literals are denoted by curly braces. The following example creates an empty object with no properties.


var animal = {};

Enter fullscreen mode Exit fullscreen mode

Inside of the curly braces, properties and their values are specified as a list of key/value pairs.
Keys can be strings or identifiers, while values can be any valid expression. The list of key/value pairs is comma delimited, with each key and value separated by a colon.

The following example creates an object with three properties using literal notation.

The first property, animal, holds the number one.
The second property, dolphin, is specified using a string, and also stores a string value. The third property, mammal, stores an empty object.


var animal = {
  dolphin: 1,
  "swim": "some string",
  mammal: {
  }
};

Enter fullscreen mode Exit fullscreen mode

Each property has been written on a separate line and indented. The entire object could have been written on a single line, but the code is more readable in this format. This is especially true for objects with many properties or nested objects.

JavaScript provides two notations for accessing object properties.

The first, and most common, is known as dot notation.
Under dot notation, a property is accessed by giving the host object's name, followed by a period (or dot), followed by the property name.

Dot Notation

Dot notation is the most common way to access properties. You simply use a dot (.) followed by the property name. For example:

The following example shows how dot notation is used to read from and write to a property. If object.dolphin
initially held the value one, then its value would become two after executing this statement.

  • Note that if animal.dolphon did not already have a value, then it would be undefined.
animal.dolphin = animal.dolphin + 1;
Enter fullscreen mode Exit fullscreen mode

The syntax for accessing object properties is known as bracket notation. In bracket notation, the object name is followed by a set of square brackets.
Inside the square brackets, the property name is specified as a string.
The previous example of dot notation has been rewritten below to use bracket notation. While the code may look different, it is functionally equivalent to the previous example.

object["dolphin"] = object["dolphin"] + 1;
Enter fullscreen mode Exit fullscreen mode

Bracket notation is more expressive than dot notation because it allows a variable to specify all or part of the property name.
This is possible because the JavaScript interpreter automatically converts the expression within the square brackets to a string, and then retrieves the corresponding property.

The following example shows how property names can be created on the fly using bracket notation. In the example, the property name foo is created by concatenating the contents of variable d, with the string "dolphin".

var d = "d";

object[d + "dolphin"] = "bar";
Enter fullscreen mode Exit fullscreen mode

Bracket notation also allows property names to contain characters that are forbidden in dot notation.
For example, the following statement is completely legal in bracket notation. However, if you tried to create the same property name in dot notation, you would encounter a syntax error.

object["!@#$%^&*()."] = true;
Enter fullscreen mode Exit fullscreen mode

Accessing Nested Properties

Properties of nested objects can be accessed by chaining dot and/or bracket references together.
For example, the following object contains a nested object named dolphin, which contains another object named mammal, which has a property named years that holds the value one.


var animal = {
  dolphin: {
    mammal: {
      years: 1
    }
  }
};

Enter fullscreen mode Exit fullscreen mode

The following expressions access the nested property, years. The first expression uses dot notation, while the second expression uses square bracket notation.
The third expression combines both notations to achieve the same result.


animal.dolphin.mammal.lungs;
animal["dolphin"]["mammal"]["years"];
animal["dolphin"].mammal["years"];

Enter fullscreen mode Exit fullscreen mode

Expressions like the ones shown in the previous example can cause performance to suffer if used improperly.
Evaluating each dot or bracket expression takes time.

If the same property is used multiple times, then it makes more sense to access the property once, and then store the value in a local variable for all future uses. The following example uses bar many times within a loop. However, instead of wasting time computing the same value over and over, bar is stored in a local variable.


var years = animal.dolphin.mammal.years;
var count = 0;

for (var i = 0; i < 100000; i++) {
  count += years;
  // better than count += animal.dolphin.mammal.years;
}

Enter fullscreen mode Exit fullscreen mode

Functions as Methods

When a function is used as an object property, it is called a method. Like properties, methods can also be specified in object literal notation. The following example shows how this is accomplished.

var animal = {
  sum: function(dolphin, years) {
    return dolphin + years;
  }
};
Enter fullscreen mode Exit fullscreen mode

Methods can also be invoked using dot and bracket notation.
The following example invokes the sum() method from the previous example using both notations.


dolphin.sum(1, 2);
dolphin["sum"](1, 2);

Enter fullscreen mode Exit fullscreen mode

Adding Properties and Methods

Object literal notation is useful for creating new objects, but it cannot add properties or methods to existing objects.
Fortunately, adding new data to an object is as simple as creating an assignment statement.

The following example creates an empty object.
Two properties, dolphin and mammal, and a method, years, are then added using assignment statements.
Note, that this example uses dot notation, but bracket notation would work equally as well.


var animal = {};
animal.dolphin = 1;
animal.mammal = null;
animal.years = function() {
  return "I am 5 years()";
};
Enter fullscreen mode Exit fullscreen mode

Summary
Objects are composite data types which are built from primitives and other objects. An object’s building blocks are commonly referred to as its fields or properties. Properties are used to describe some aspect of an object. For example, a property can describe the length of a list, the color of a dog, or a person’s date of birth.
So JavaScript object syntax is crucial to be understood, as it serves as a foundation of the language.
As first you need to understand objects before you can understand object-oriented programming.

  • Dot Notation: Use when property names are valid identifiers.
  • Bracket Notation: Use when property names are dynamic or not valid identifiers. These accessors are fundamental in JavaScript for manipulating objects and their properties effectively.

Happy Coding!

Top comments (0)