Open In App

JavaScript Objects

Improve
Improve
Like Article
Like
Save
Share
Report

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.

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

javascript




// Create string primitive.
let strPrimitive = "GeeksforGeeks";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false
  
// Use the Built-in String Function as Constructor.
let strObject = new String( "GeeksforGeeks" );
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: "GeeksforGeeks",
  
    // Object Property (Date).
    obj_prop: new Date(),
  
    // Object Property.
    inner_obj: {
        int_prop: 6
    },
  
    // Function Property.
    func_prop: function() {
        console.log("Welcome to GeeksforGeeks!");
    }
};
  
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
GeeksforGeeks
5:47:55 PM
6
Welcome to GeeksforGeeks!

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(" - GeeksforGeeks.org");
    }
}
  
myObj.greet();
myObj.byWhom();


Output:

Hello There!
 - GeeksforGeeks.org

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.



Last Updated : 23 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads