Object Literal in JavaScript

Object Literal in JavaScript with Examples

In this article, I am going to discuss Object Literal in JavaScript with Examples. Please read our previous article where we discussed JavaScript Object Methods. At the end of this article, you will understand what is Object Literal in JavaScript is and when and how to use an Object Literal in JavaScript with examples.

Object Literal in JavaScript

JavaScript allows us to define methods of an object using the object literal syntax. Objects contain properties, which are used to describe an object. Values of object properties can either contain primitive data types, like strings, numbers, and Booleans, or other objects/complex data types like arrays, functions, or other objects. We might wonder, what Object Literals are, more importantly, why we even need them.

In plain English, a JavaScript object literal also called an object initializer, is a list of key-value pairs comma-separated inside of curly braces {}, with the keys and the values separated by colons (:). Property has a key (also known as “name” or “identifier”) placed before the colon “:” and a value to the right of it.

Key-value pairs of an object are also referred to as properties. Those values can be properties and functions. All the keys are unique, but the values are not.

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.

Syntax:
let objectName = {};// "object literal" syntax /create an empty object
or
//initialize an object with properties/key-value pairs
var objectName = { property1: value1, property2: value2....propertyN: valueN }

As we can see, property and value are separated by: (colon). The curly braces ({}) are an object. We just have created our first object. We can also initialize an object with key-value pairs with {key: value} syntax.

Properties of a JavaScript object can be accessed using a dot notation(.) or bracket notation [ ]. For Example, objectName.propertyName or objectName[‘propertyName’] 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.

Use the following syntax to create an object method:

methodName : function () { //code here},

Access an object method using the following syntax:

objectName.methodName();

We can declare the properties and methods listed using cleaner Object Literal syntax as follows:

var myObject = {
            myProperty: value,
            secondProperty: value,
            myMethod: function () {
                //code here
            },
            secondMethod: function () {
                //more code
            }
        }

//Access an object method
myObject.myMethod();
myObject.secondMethod();
How to Create an Object?
  1. Add a variable declaration for the object here in the above sample object name is myObject.
  2. Next, start an object with a left curly brace { ­­.
  3. Then all the object’s properties go inside.
  4. Each property has a name/key, a colon (:), and then a value. We can have strings, numbers, Boolean, or any primitive or non-primitive data types as property values.
  5. Notice that each property is separated by a comma.
  6. We end the object with the closing curly brace }, and just like any other variable declaration, we end this one with a semicolon.

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. Spaces and line breaks are not important. Hence the object can be written like this:

let lecture = { course: ‘JavaScript’, version: ‘ES6’, language: ‘Scripting’ };

An object definition can span multiple lines; thus, the above object could also be written like this:

let lecture = {
    course: 'JavaScript',
    version: 'ES6',
    language: 'Scripting'
};

No matter how the object is created, the syntax for accessing the properties and methods does not change. They can be accessed using a dot notation(.) or bracket notation [ ]. JavaScript allows us to define methods of an object using the object literal syntax. ES6 also provides us with the concise method syntax that allows us to define a method for an object. What we discussed above is given in the below example.

Example: JavaScript defines a function to person object using object literal
<html>
<head>
    <title>JavaScript defines a function to person object using object literal example </title>
</head>
<body>
    <script>
        //Way3-By Object literal
        //sample1 code -- "object literal" syntax, create an object       
        let employee = {};
        employee.name = 'Kathy';
        employee.age = 20;
        employee.bloodgroup = 'B+';
        
        //define methods of an object using the object literal syntax. 
        employee.greet = function (who) {
            alert('Hello,' + who + '!')
        };

        //sample2 code-- initialize an object with key-value pairs, create an object
        const person = {
            name: 'John ',
            age: 15,
            bloodgroup: 'A+',

            //define methods of an object using the object literal syntax. 
            greet: function (who) {
                alert('Hello,' + who + '!')
            },
            
          //ES6 provides the concise method syntax that allows defining an object method
            greet1() {
                alert('Hello, JavaScript ES6');
            }
        };

        //call the object method with argument
        employee.greet(employee.name);
        person.greet(person.name);
        person.greet1();
    </script>
</body>
</html>
Output:

Object Literal in JavaScript with Examples

Where to use Object Literals or why do we need them?
  1. Use the object literal or initializer syntax to create single objects.
  2. Object literal syntax can be used to initialize the entire object.
  3. 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.
  4. For creating a code that is easy to use and easily readable.
  5. It is easier and more structured to create objects quickly.
  6. When we want to use symbols as property names of objects it makes it to create 100% unique properties.
Advantages of Object Literal
  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.

In the next article, I am going to discuss JavaScript Constructor Function with Examples. Here, in this article, I try to explain Object Literals in JavaScript with Examples. I hope you enjoy this Object Literal in JavaScript article. 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. Required fields are marked *