JavaScript Object Literals

JavaScript Object Literals with Examples

In this article, I am going to discuss JavaScript Object Literals with Examples. Please read our previous article where we discussed JavaScript Template Literals. The object literal is one of the most powerful approaches for creating objects in JavaScript with properties enclosed with curly braces. JavaScript ES6 introduces the object literals features for creating objects in JavaScript make object handling even easier in all modern browsers by extending the syntax in some ways. At the end of this article, you will understand the following pointers with examples.

  1. Object Literals in JavaScript
  2. Features of Object Literals in JavaScript
  3. Where to use Object Literals or why do we need Object Literals in JavaScript?
  4. Advantages of JavaScript Object Literals
  5. JavaScript Object Literals Computed Property Names /Dynamic Property Keys
  6. JavaScript Object Literals Rest or Spread Properties
  7. JavaScript Object Literals Short Methods/ Method Shorthand
Object Literals in JavaScript

You might wonder, what Object Literals are, and more importantly, why do we even need them? In plain English, an object literal is a list of name-value pairs comma-separated inside of curly braces. Those values can be properties and functions.

The object literal notation is mainly an array of key: value pairs, with a colon (:) separating the keys and values, and a comma (,) after every key: value pair, except for the last item we don’t need to put a comma after that, just like a regular array. Values created with anonymous functions are methods of an object and simple values are properties.

Object Literals Syntax:

Object Literals Syntax

Properties of a JavaScript object can be accessed using a dot notation(.) or bracket notation [ ]. For Example, course.name or course[‘name’] will give us the value.

All members of an object literal in JavaScript, both properties and functions, are public. The only place we can put private members is inside of a function. We can declare the properties and methods listed using cleaner Object Literal syntax:

Syntax:

JavaScript Object Literals

When we assign an object literal to another variable it only performs a shallow copy, which means we get the reference of the object instead of the actual value.

Example: JavaScript Object literal Example
<html>
<head>
    <title>JavaScript Object literal example</title>
</head>
<body>
    <script>
        //with ES6
        //sample1 code
        let course = {};// "object literal" syntax
        course = {
            name: "JavaScript", // by key "name" store value "JavaScript"
            language: 'scripting' // by key "language" store value "scripting"
        };

        console.log("Object Literal - Course object: ", course)
        console.log("Object Literal - key value1: " + course.name + " is a " + course.language);
        console.log("Object Literal - key value: " + course['name'] + " is a " + course['language']);
        console.log("Object Literal - Course object length: ", Object.getOwnPropertyNames(course).length)
        console.log("Course Object literal type? : ", typeof course);// string

        //sample2 code
        let lecture = {};// "object literal" syntax
        lecture.course = 'JavaScript';
        lecture['version'] = 'ES6';
        lecture.language = 'Scripting'

        console.log("Object Literal - Lecture object: ", lecture)
        console.log("Object Literal - key value: " + lecture.course + " with version " + lecture.version + " is a " + lecture.language);
        console.log("Object Literal - key value: " + lecture['course'] + " with version " + lecture.version + " is a " + lecture.language);
        console.log("Object Literal - lecture object length: ", Object.getOwnPropertyNames(lecture).length)
        console.log("lecture Object literal type? : ", typeof lecture);// string

    </script>
</body>
</html>

Output: Run the application and open the browser developer’s tool and then select the console tab as shown in the below image.

JavaScript Object literal Example

Features of Object Literals in JavaScript
  1. Instead of { name: name }, we can just do { name } — known as a property value shorthand
  2. Computed property names, { [prefix + ‘Test’]: ‘cat’ }, where prefix: ‘prod’, yields { prodTest: ‘cat’ }
  3. We can’t combine computed property names and property value shorthand’s, { [test] } is invalid
  4. Method definitions in an object literal can be declared using an alternative, more terse syntax, { test () {} }
  5. The object literal notation is mainly an array of key: value pairs, with a colon (:) separating the keys and values, and a comma (,) after every key: value pair, except for the last item we don’t need to put a comma after that, just like a regular array. Values created with anonymous functions are methods of an object and simple values are properties
  6. If we are mixing source codes, using libraries, or sharing code, we want to use static methods and properties rather than public methods and properties, to safeguard against overwriting functions or variables/methods or properties declared outside our current JavaScript file.
  7. Unlike public functions, which can appear anywhere in our code, including after lines using our function, methods declared using object literal notation do not exist until execution of that section of the script
  8. This method instantiates a new object, so don’t try to create an instance using the new keyword
  9. All members of an object literal in JavaScript, both properties and functions, are public. The only place we can put private members is inside of a function.
  10. When we assign an object literal to another variable it only performs a shallow copy, which means we get the reference of the object instead of the actual value.
Where to use Object Literals or why do we need Object Literals in JavaScript?
  1. When we want to create objects on the go with no purpose of copying values to another object or maybe mapping one object to another.
  2. For creating a code that is easy to use and easily readable.
  3. It is easier and more structured to create objects quickly
  4. When we want to use symbols as property names of objects which makes it to create 100% unique properties.
Advantages of JavaScript Object Literals
  1. It provides a shorter syntax for creating/initializing properties from variables (Property Shorthand).
  2. It provides a shorter syntax for defining function methods.
  3. It enables the ability to have computed property names in an object’s literal definition.
Object property initializer shorthand / Short Properties / Property Value Shorthand’s /Duplicate property names /Object Initialization from variables

Before ES6, an object literal is a list of name-value pairs comma-separated inside of curly braces. In ES6 Whenever we assigning a property value that matches a property name, we can omit the property value, it’s implicit (automatic) in ES6. As ES6 allows to remove the duplication when a property value of an object is the same as the variable name/property name by including the name without the colon and value.

When using the same name for properties, the second property will overwrite the first one. This is called duplicate property name removal features of object literals. Objects’ properties are often created from variables with the same name. it is called Object Initialization from variables.

Example: JavaScript Object Literal-Property shorthand Example
<html>
<head>
    <title>JavaScript Object Literal-Property shorthand example</title>
</head>
<body>
    <script>
        //before ES6 old syntax
        const x = 10, y = 20;
        const oldObj = {
            x: x,
            y: y
        }
        console.log("Before ES6- Property Shorthand: ", oldObj)
        console.log("Before ES6- Property Shorthand: " + "value of x: " + oldObj.x + " value of y: " + oldObj.y)

        //with ES6 new syntax
        const a = 10, b = 20;
        const newObj = {
            a, b
        }
        console.log("With ES6- Property Shorthand: ", newObj)
        console.log("With ES6- Property Shorthand: " + "value of a: " + newObj.a + " value of b: " + newObj.b)

        //same name for properties, the second property will overwrite the first.
        let c = { z: 1, z: 2 }
        console.log("Same name for properties, the second property will overwrite the first: ", c); // {z: 2}
    </script>
</body>
</html>
Output:

JavaScript Object Literal-Property shorthand Example

Computed Property Names /Dynamic Property Keys

Prior to ES6 in ES5 and earlier, we could not use a variable as a property name inside an object literal. The only way we had was to create the object literal then assign the variable property name with value and pass the resulting object to the animate method. ES6 defines ‘ComputedPropertyName’ as part of the object literals, which helps use a variable for an object key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets [ ].

Computed property names allow us to write an expression enclosed in square brackets [ ] instead of the regular property name. Whatever the expression is it will be computed and will be used as the property name. The limitation of computed property names is that we won’t be able to use the shorthand expression with it. Other types are automatically converted to strings.

Computed Property Names /Dynamic Property Keys Syntax:

Computed Property Names /Dynamic Property Keys Syntax

A dynamic key can be used for methods as well as properties.

Example1: JavaScript Object Literal-Computed Property Names
<html>
<head>
    <title>JavaScript Object Literal-Computed Property Names Example</title>
</head>
<body>
    <script>
        //before ES6 old syntax
        const propertyName = 'Property1';
        const computed_property_Name = () => 'Property-3*' + 3;

        const oldObj = {};
        oldObj[propertyName] = 'string';
        oldObj[computed_property_Name()] = 3 * 3;
        console.log("Before ES6- Computed Property Names: ", oldObj)

        //With ES6 new syntax
        const propName = 'Prop1';
        const computed_prop_Name = () => 'Property-3*' + 3;

        const newObj = {
            [propName]: 'str',
            [computed_prop_Name()]: 3 * 3
        };
        console.log("With ES6- Computed Property Names: ", newObj)

    </script>
</body>
</html>
Output:

JavaScript Object Literal-Computed Property Names

Any expression can be used to create a key. For example, below sample code no-4 elaborate.

Example2: JavaScript Object Literal-Computed Property Names
<html>
<head>
    <title>JavaScript Object Literal-Computed Property Names Example</title>
</head>
<body>
    <script>
        //sample1 code
        var key = "Dynamic Property Names";
        var object = {};
        object[key] = "JavaScript";
        console.log("With ES6- Computed Property Names-sample code1: ", object)

        //sample2 code
        var key1 = "Dynamic Property Names";
        var object1 = {
            [key1]: "JavaScript"
        };
        console.log("With ES6- Computed Property Names-sample code2: ", object1)

        //sample3 code
        let name = 'Weekday name';
        let Week = {
            [name]: 'Monday',
            'day hours': 24
        };
        console.log("With ES6- Computed Property Names-sample code3: ", Week)
        console.log('Week name is: ', Week[name]); // Monday
        console.log('Day hours is ', Week['day hours']); // 24

        //sample4 code
        let i = 0
        let dynamicObjKey = {
            ['welcome' + ++i]: i,
            ['welcome' + ++i]: i,
            ['welcome' + ++i]: i
        }
        console.log("With ES6- Computed Property Names-sample code4: ", dynamicObjKey)
        console.log('dynamicObjKey welcome1 value: ', dynamicObjKey.welcome1) // 1
        console.log('dynamicObjKey welcome1 value: ', dynamicObjKey.welcome2) // 2
        console.log('dynamicObjKey welcome1 value: ', dynamicObjKey.welcome3) // 3

        //sample5 code
        const items = ["Notebook", "Pen", "Laptop"];
        const obj = {
            [items]: "Item Lists"
        }
        console.log("With ES6- Computed Property Names-sample code5: ", obj)//Notebook,Pen,Laptop: "Item Lists"
        console.log('obj items key value is: ',obj[items]) // Item Lists
    </script>
</body>
</html>
Output:

JavaScript Object Literal-Computed Property Names Example

JavaScript Object Literals Rest or Spread Properties

In ES2015(ES6), rest parameter and spread operator three-dot (…) notation applied to arrays only. Whereas ES2018 provides similar rest/spread functionality for objects. ES2018(ES9) adds spread properties to object literals. It copies its own enumerable properties from a given object onto a new object.

Prior to ES6, Shallow-cloning or merging objects was done using Object.assign(). But now Shallow-cloning or merging objects is now possible using a shorter syntax with the help of the rest/spread operator.

When we assign an object literal to another variable it only performs a shallow copy, which means we get the reference of the object instead of the actual value.

Example1: JavaScript Object Literal-Spread properties Example
<html>
<head>
    <title>JavaScript Object Literal-Spread properties Example</title>
</head>
<body>
    <script>
        //before ES6 old syntax
        const x = { a: 10, b: 20 }
        const y = { c: 30, d: 40 }
        const xy = Object.assign(x, y)
        console.log("Before ES6- Object Literal-Spread properties: ", xy)

        //With ES6 new syntax
        const x1 = { a: 10, b: 20 }
        const y1 = { c: 30, d: 40 }
        const xy1 = { ...x1, ...y1 }
        console.log("With ES6- Object Literal-Spread properties: ", xy1)

    </script>
</body>
</html>
Output:

JavaScript Object Literal-Spread properties Example

Example2: JavaScript Object Literal-Spread properties (cloned and merged) Example
<html>
<head>
    <title>JavaScript Object Literal-Spread properties (cloned and merged) Example</title>
</head>
<body>
    <script>
        let object1 = { greeting: 'Good morning', time: 7 }
        let object2 = { greeting1: 'Good Afternoon', time1: 4 }
        let object3 = { greeting1: 'Good evening', time2: 8 }

        let clonedObj = { ...object1 }
        // Object { greeting: 'Good morning', time: 7 }

        let mergedObj = { ...object1, ...object2, ...object3 }
        // Object {greeting: "Good morning", time: 7, greeting1: "Good evening", time1: 4, time2: 8}

        console.log("Object Literal-Spread properties-Clone object: ", clonedObj)
        console.log("Object Literal-Spread properties-Merged object: ", mergedObj)
    </script>
</body>
</html>
Output:

JavaScript Object Literal-Spread properties (cloned and merged) Example

JavaScript Object Literals Short Methods/ Method Shorthand

All members of an object literal in JavaScript can be both properties and functions, they are public. The only place we can put private members is inside of a function. Prior to ES6, when creating a method for an object literal, we need to specify the function name and function definition as shown in the below example.

This is no longer necessary for function names and function statements in ES6; it allows the shorthand syntax.ES6 makes the shorter syntax for creating a method of the object literal shorter by removing the colon (:) and the function keyword. This shorthand syntax is also known as the short method syntax.

JavaScript Object Literals Short Methods/ Method Shorthand Syntax:

To call a method, we need to use the following syntax.

JavaScript Object Literals Short Methods/ Method Shorthand Syntax

Example1: JavaScript Object Literal-Short Methods Example
<html>
<head>
    <title>JavaScript Object Literal-Short Methods Example</title>
</head>
<body>
    <script>
        //before ES6 old syntax
        const oldObj = {
            a: 10,
            b: 20,
            sum: function () { return this.a + this.b }
        }
        console.log('before ES6 Object Literal-Short Methods=>sum() is: ', oldObj.sum());

        //with ES6 new syntax
        const newObj = {
            x: 10,
            y: 20,
            sum() { return this.x + this.y }
        }
        console.log('with ES6 Object Literal-Short Methods=>sum() is: ', newObj.sum());

    </script>
</body>
</html>
Output:

JavaScript Object Literal-Short Methods Example

Example2: JavaScript Object Literal-Short Methods Example
<html>
<head>
    <title>JavaScript Object Literal-Short Methods Example</title>
</head>
<body>
    <script>
        //sample code1
        let machine = {
            name: 'WindowServer',
            restart() {
                console.log(`The ${this.name} is restarting!`);
            },
            'patching up'() {
                console.log(`The ${this.name} is starting up!`);
            },
            shutdown() {
                console.log(`The ${this.name} is shutting down`);
            }
        };

        console.log('Sample Code1:')
        console.log('Object Literal-Short Methods-Machine restart: ', machine.restart());
        console.log('Object Literal-Short Methods-Machine Patching up: ', machine["patching up"]());
        //console.log('Object Literal-Short Methods-Machine shutdown: ', machine.shutdown());

        //sample code2
        const driver = {
            name: "Maria",
            speed: 60,
            car: "Audi",
            speedUp(speedup) {
                this.speed = this.speed + speedup;
                console.log("new speed = " + this.speed)
            }
        }
        console.log('Sample Code2:')
        console.log('Object Literal-Short Methods-Driver speed: ', driver.speedUp(10));
    </script>
</body>
</html>
Output:

JavaScript Object Literal-Short Methods Example

Symbols as Property Names

This we already have learned about Symbol in Symbol Chapter. At first glance, Symbols seem meaningless. But in combination with objects and especially the dynamic property names feature makes them really powerful.

The symbol is a new primitive data type and a symbol is never equal to another symbol. Symbols can also be used as property names of objects. Which makes it possible to create 100% unique properties, therefore avoiding our code interfering with another program code.

In the next article, I am going to discuss JavaScript Default Parameters with Examples. Here, in this article, I try to explain the JavaScript Object Literals with Examples. I hope this JavaScript Object Literals with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.