Open In App

JavaScript Objects

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.

let obj = {
    key1: value1,
    key2: value2,
    ...
};
function obj(value1, value2, ...) {
    this.key1 = value1;
    this.key2 = value2;
    ...
}
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. 




// 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, 




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. 




// 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:

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.


Article Tags :