In our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don’t exist in JavaScript. In this article, objects are discussed in detail.

Creating Objects:

In JavaScript, Objects can be created using two different methodologies namely Literal Form and Constructed Form.

  • Literal Form: The literal form uses the construction of object literals that can be said as a collection of key-value pairs enclosed within a pair of curly braces. The syntaxial form is shown below.
let obj = {
    key1: value1,
    key2: value2,
    ...
};
  • Constructed Form: The Constructed form uses either an object constructor function or the new keyword to create an empty object ad then adds properties to the object one by one. The syntaxial forms are shown below.
    • Object Constructor Function: In this methodology, the user creates an explicit function to take required values as parameters and assign them as the properties of the desired object.
function obj(value1, value2, ...) {
    this.key1 = value1;
    this.key2 = value2;
    ...
}
  • Using New Keyword: This methodology uses the New keyword in front of any constructor method or any built-in constructor method (such as Object, Date, String, etc.) and creates a new instance of the following object by mounting it on memory.
let obj = new Object();
obj.key1 = value1;
obj.key2 = value2;
...

Differences between using Object Literals and the Constructed Form: Both the constructed form and literal form result in creating exactly the same sort of object i.e. the end result is the same for both methodologies. The only difference between the both is that object literals can take care of several key-value pairs at once and thus is more convenient while on the other hand with the constructed-form objects, we must add the properties one-by-one in separate statements.

Note: It is highly uncommon to use the Constructed Form over the Object Literals for creating objects, hence for any further illustrations we will be using the object literals on most occasions.

Built-In Objects:

JavaScript consists of a bunch of Built-In Objects, the following list explores most of them. Although these built-ins have the appearance of being actual types or classes like in any other OOP, in JavaScript these are only functions that can be used as constructors to create objects of the particular sub-type.

  • Array
  • Date
  • RegExp
  • Error

Now let us take an example to differentiate between Objects and Primitives.

JavaScript

// Create string primitive.
let strPrimitive = "CodeConfig.in";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false
 
// Use the Built-in String Function as Constructor.
let strObject = new String( "CodeConfig.in");
typeof strObject; // "object"
strObject instanceof String; // true
 
// inspect the object sub-type
Object.prototype.toString.call( strObject ); // [object String]

In the above example, we saw that creating a string primitive didn’t create an object or an instance of a String. Primitives are literal and immutable values, to perform tasks like calculating the length or changing any character at any position we must use the Object of type String. But JavaScript is a dynamic language and luckily for the developers, JavaScript coerces a string primitive to a String class whenever any operation needs it to be. It is to be noted, that due to internal coercion it is vastly preferred to use primitives as much as possible instead of objects.

Content of Objects:

JavaScript objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. The Property Value can be of the primitive data type or an object or even a function. The property can also be globally accessible in spite of being owned by an object. The general syntax of defining an object property is as shown below,

objectName.objectProperty = propertyValue;

The following program will clear the concepts we discussed above,

JavaScript

let myObj = {
    // Integer Property.
    int_prop: 5,
 
    // String Property.
    str_prop: "CodeConfig.in",
 
    // Object Property (Date).
    obj_prop: new Date(),
 
    // Object Property.
    inner_obj: {
        int_prop: 6
    },
 
    // Function Property.
    func_prop: function() {
        console.log("Welcome to CodeConfig.in!");
    }
};
 
console.log(myObj.int_prop);
console.log(myObj.str_prop);
console.log(myObj.obj_prop.toLocaleTimeString());
console.log(myObj.inner_obj.int_prop);
myObj.func_prop();

Output:

5
CodeConfig.in 9:41:55 PM 7 Welcome to CodeConfig.in!

As per conventions, functions associated with an object are known as methods. This is considered to be a small difference between a function and a method. A function is an independent sequence of a bunch of statements whereas a method is associated with an object and is generally referenced by this keyword.

Defining Global Variables to be owned by Objects: This is mostly done on methods, the process is fairly simple we will define our function as we are used to, and while defining the function to be a member of the object properties we will just give the name of the function as the value of one key. Let us see the example given below.

JavaScript

// Define Function Explicitly.
function toGreet() {
    console.log("Hello There!");
}
 
let myObj = {
 
    // Mention Function-Name as Value.
    greet: toGreet,
 
    // Define Function implicitly.
    byWhom: function() {
        console.log(" - CodeConfig.in");
    }
}
 
myObj.greet();
myObj.byWhom();

Output:

Hello There!
 - CodeConfig.in

Note: The ‘with’ keyword can be used to reference an object’s properties. The object specified as an argument to with becomes the default object for the duration of the block that follows. This is generally recommended not to be used by developers. The use of with is not allowed in JavaScript strict mode. 

Important Points:

  • Date values can only be created with their constructed object form, as they have no literal form.
  • Objects, Arrays, Functions, and RegExps (regular expressions) are all objects regardless of their creation methodologies i.e. whether the literal or constructed form was used to create them.
  • The constructed form may offer more customization while creating an object, this is the sole advantage over using the literal form.

With this, we can end this discussion about Objects in JavaScript and can start walking on the Path of defining and describing important topics related to objects.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, CodeConfig.in Courses are your key to success. We provide top-quality content at no cost, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Explore More

How to Center a Popup Window on Screen

JavaScript window.open() method is used to open a popup window. This popup window will be placed in the center of the screen. This example creates the pop-up window without placing it into

How to hide URL in the popup window opened using window.open

If you are using below code to open a popup window in your web page, then address must be appearing in you pop up window and f you want to

window.showModalDialog is deprecated in Edge and Chrome

If you have a website being compatible with Edge/Chrome and in past it was only compatible with IE 11 and if you are using window.showModalDailog in your JavaScript code, then