JavaScript object Using object literal

Creating JavaScript object Using object literal with Examples

In this article, I am going to discuss How to Create a JavaScript Object Using an Object Literal with Examples. Please read our previous article where we gave an overview of JavaScript Objects.

Object Creation in JavaScript

Objects are one of the core concepts in JavaScript. JavaScript objects are containers for named(key) values called properties or methods.

An object can be created with curly brackets {…} with a list of properties. A property is a “key: value” pair, where the key is a string (also called a “property name”), and value can be any data type like strings, numbers, Booleans, or complex data types like arrays, functions, and other objects. with the names(keys) and the values separated by colons (:).

Understanding the creation of objects is essential. JavaScript objects can be created in various ways which are as follows.

  1. Using object literal
  2. Using new Object() method /By creating an instance of Object directly (using the new keyword)
  3. Using an object constructor (using the new keyword)
  4. Using Object.create() method
  5. Using Factory Pattern/ Object Building Function
  6. Using Prototype Pattern

We can access the properties of the object,

  1. By Dot operator/ dot notation (.) Example: objectName.propertyName
  2. By Square brackets/ bracket notation/ Array-like notation ([]). Example: objectName[‘propertyName’]
Creating JavaScript Object Using Object Literal

Objects contain properties, which are used to describe an object. Values of object properties can either contain primitive data types, like strings, numbers, Booleans, or other objects/complex data types like arrays, functions, and other objects. We might wonder, what Object Literals are, and more importantly, why do 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 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:

Creating JavaScript Object Using Object Literal Syntax

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. We can declare the properties and methods listed using cleaner Object Literal syntax:

Syntax:

Creating JavaScript Object Using Object Literal Syntax

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 [ ].

Example: Objects in JavaScript by Object literal
<html>
<head>
    <title>Objects in JavaScript by Object literal example</title>
</head>
<body>
    <script>
        console.log('sample1 code with object literal syntax');
        //sample1 code
        // "object literal" syntax, create an object       
        let course = {};
        course.name = "JavaScript";// by key "name" store value "JavaScript"
        course.language = 'scripting'; // by key "language" store value "scripting"

        console.log("Object Literal - Course object: ", course)
        console.log("Object Literal - with dot notation-->Property name value is: " + course.name);
        console.log("Object Literal - with dot notation-->Property language value is: " + course.language);
        console.log("Object Literal - with bracket notation-->Property name value is: " + course['name']);
        console.log("Object Literal - with bracket notation-->Property language value is: " + course['language']);
        console.log("Object Literal - Course object length: ", Object.getOwnPropertyNames(course).length)
        console.log("Course Object literal type? : ", typeof course);// object

        console.log('sample2 code with initialize an object with key-value pairs syntax');
        //sample2 code
        //initialize an object with key-value pairs, create an object
        let lecture = {
            course: 'JavaScript',
            version: 'ES6',
            language: 'Scripting'
        }

        console.log("Object Literal - Lecture object: ", lecture)
        console.log("Object Literal - key course value: " + lecture.course + ", with key version value: " + lecture.version + " is a " + lecture.language);
        console.log("Object Literal - key course value: " + lecture['course'] + ", with key 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);// object
    </script>
</body>
</html>
Output:

Objects in JavaScript by Object literal

We can add properties dynamically in an object, including after we have created the object. Here we add the dynamic property course.name to the object course. After creating the object, we can get the properties of the object with dot notation or bracket/array notation.

In the above example, Sample1 code contains 2 properties to course object, in the first property name is the key and JavaScript is the value and in the second property, language is the key and scripting is the value. We can get the value of name properties with the course.name, we can also access the properties with square bracket course[‘name’]

Similarly, in Sample2 code there are 3 properties assign to the lecture object, in the first property course is the key and JavaScript is the value, the 2nd property has the version as key and ES6 as value. Later for 3rd property, we have language as the key and Scripting as the value.

Creating JavaScript object Using object literal 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 which makes it to create 100% unique properties.
Advantage 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.

Note that all keys in JavaScript objects are strings. All keys in JavaScript objects are strings and can be only a string. If it’s not a string. It gets cast/converted to a string. This means that even though we can create an object {1: ‘is the real number’}, the key here, 1 gets turned into the string ‘1’. Values can be of any type.

Note that keys must be unique, but values are not. As we know that Object is like a dictionary and it contains a unique key and value mapped to that key. And due to the uniqueness of each stored key, there is no duplicate pair stored. If the key already exists in the object, it will not be added again, as the object contains unique keys and values mapped to that key.

Setting a key over and over again meaning setting a duplicate key will overwrite its value with a new one. If we were to initialize the following object

Where to use Object Literals or why do we need them in JavaScript?

And then check on the value of lecture, we would see

Advantage of Object Literal in JavaScript

What we discussed above is given in the below example.

Example: JavaScript Object with the unique key
<html>
<head>
    <title>JavaScript Object with unique key example</title>
</head>
<body>
    <script>
         let lecture = {
            course: 'JavaScript',
            course: 'TypeScript',
            version: 'ES6',
            language: 'Scripting'
        }         
        console.log('JavaScript Simple Object with unique key: ', lecture);
        console.log('Type of variable lecture: ', typeof lecture)
    </script>
</body>
</html>
Output:

JavaScript Object with the unique key

In the above example, in the lecture object, setting a key course over and over again meaning setting a duplicate key will overwrite its value with a new one. Here, it will overwrite the old value JavaScript with the new one TypeScript. As we learned, all the keys are unique, but Values don’t have to be unique, though we can assign the same values to all the object keys. What we discussed above is given in the below example.

Example: JavaScript Object, keys are unique but value doesn’t have to be
<html>
<head>
    <title>JavaScript Object, keys are unique but value don't have to be example</title>
</head>
<body>
    <script>
        let lecture = {
            course: 'JavaScript',
            version: 'JavaScript',
            language: 'JavaScript'
        }
        console.log("JavaScript Simple Object with keys are unique but value don't have to be:\n ", lecture);
        console.log('Type of variable lecture: ', typeof lecture)
    </script>
</body>
</html>
Output:

JavaScript Object, keys are unique but value doesn’t have to be

Use Variable as Object Key/ Computed Property Names. Similarly, if we have a variable const tutorial = ‘course’ and tried to create an object

How to Create JavaScript Object Using object literal with Examples

The lecture object’s key would be ‘tutorial’, not ‘course‘. What we discussed above is given in the below example.

Example: JavaScript Object, using a variable as the object key
<html>
<head>
    <title>JavaScript Object, using a variable as object key example</title>
</head>
<body>
    <script>
        const tutorial = 'course';

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

        console.log('JavaScript Simple Object, using variable as object key:\n ', lecture);
        console.log('Type of variable lecture: ', typeof lecture)
    </script>
</body>
</html>
Output:

JavaScript Object, using a variable as the object key

Best Tip: JavaScript ES6 provides a way to use variables as object keys — we have to wrap the key in square brackets ([]) also called Computed property names. Using the above example, we could write const tutorial = ‘course’

Creating JavaScript Object Using object literal with Examples

Pretty cool, isn’t it? What we discussed above is given in the below example.

Example: JavaScript Object, wrap the key in square brackets to use a variable as the object key
<html>
<head>
    <title>JavaScript Object, wrap the key in square brackets to use variable as object key (Computed property names) example</title>
</head>
<body>
    <script>
        const tutorial = 'course';

        let lecture = {
            [tutorial]: 'JavaScript',
            version: 'ES6',
            language: 'Scripting'
        }

        console.log('JavaScript Simple Object, wrap the key in square brackets to use variable as object key:\n ', lecture);
        console.log('Type of variable lecture: ', typeof lecture)
    </script>
</body>
</html>
Output:

JavaScript Object, wrap the key in square brackets to use a variable as the object key

Rules of the road for creating objects literal

1. Make sure we enclose our object in curly braces:
var car = {
     model: ‘BMW’
};

2. Separate the property name and property value with a colon (:) :
var covid = {
      year: 2020
};

3. A property name can be any string, but we usually stick with valid variable names:
var widget = {
      cost$: 3.14,
     “on sale”: true
};
Notice that if we use a string with a space in it for a property name, we need to use quotes around the name. That can only be accessed using the square bracket notation [ ].

4. No two properties in an object can have the same name:
var weatherForecast = {
   highTemp: 45,
   highTemp: 40 //this won’t work
};

5. Separate each property name and values pair with a comma:
var bike = {
    model: ‘pulsar’,
   color: ‘black’
};

6. Don’t use a comma after the last property value:
var month = {
     name: ‘April’,
     season: ‘summer’ //no comma needed here.
};

In the next article, I am going to discuss how to create a JavaScript object using the new Object() method. Here, in this article, I try to explain How to Create JavaScript Object Using Object Literal with Examples and I hope you enjoy this Creating JavaScript Object Using an object literal article.

Leave a Reply

Your email address will not be published. Required fields are marked *