JavaScript Object Literals

Object literals in JavaScript provide a means to group together associated variables and functions into one package, making them easier to use and manage. They are defined by name, with the variables and functions enclosed in curly braces, as key and value pairs, known as properties.

const objectLiteralName = {
   property1: value1,
   property2: value2,
   property3: value3
};

The value of a property can be of any data type, including a reference to another object literal and a function.

Below is an example of an object literal, called 'greeting', with two properties, 'message' and 'name', the latter of which has a value set to an empty string.

const greeting = {
   message: "Hello",
   name: ""
};

Properties in an object literal can be accessed using either dot notation or bracket notation, as shown in the examples below, which access the value of the 'message' property and display it.

document.write(greeting.message);
document.write(greeting['message']);

Setting the value of a property is similar to setting the value of an ordinary variable, using the equals sign. Again, either dot or bracket notation can be used.

greeting.name = "Fred";
greeting['name'] = "Fred";

It is also possible to add a property to an object literal after it has been defined, by specifying a new property name and value.

greeting.age = 35;
greeting['age'] = 35;

This can then be accessed in the same way as any other property, as shown in the examples below, where the 'name' and 'age' properties are incorporated into a sentence.

document.write(greeting.name + " is " + greeting.age + " years old.");
document.write(greeting['name'] + " is " + greeting['age'] + " years old.");

As mentioned above, the value of a property can actually be set to a function, which performs a specific task. Here, the 'message' property, along with the 'name' property, if it is set, is incorporated into a greeting, within a function called 'display'. Notice that, within the function, the object literal name is replaced by the 'this' keyword, when referring to a property.

const greeting = {
    message: "Hello",
    name: "",
    display: function() {
        if (!this.name) {
            return this.message;
        } else {
            return this.message + " " + this.name;
        }
    }
};

This function can again be called by using either dot or bracket notation. 

document.write(greeting.display());
document.write(greeting['display']());