Enroll in Selenium Training

An object is a non-primitive data type that represents a collection of properties and the methods which manipulate and expose those properties. In other words, we can think of an object as a list that contains items, and a name-value pair store each item in the list. In other programming languages like Java, you need a class to create an object of it. Here, in JavaScript, an object is a standalone entity because there is no class in JavaScript. In this article, we will cover the following aspects of the JavaScript Objects:

  • What are Objects in JavaScript?
    • Properties in JavaScript Object
    • Methods in JavaScript Object
  • How to create Objects in JavaScript?
  • What are the methods provided by JavaScript Objects?

What are JavaScript Objects?

Objects in JavaScript, similar to other programming languages, can be compared to real-life objects. In JavaScript, an object is a standalone entity with properties and methods. Consider the example of a cup of tea, where a cup is an object with properties. We can clearly say that the cup has a color, design, weight, material, etc. In the same vein, JavaScript objects can have properties, which define their characteristics.

The objects are quite different from JavaScript's primitive data-types(Number, String, Boolean, null, undefined, and symbol), and the following facts make it more clear:

  • Objects pertain to more complex structures compared to primitive data types. Additionally, each object may contain any combination of these primitive data-types, as well as a reference to these data-types.
  • Moreover, an object is a reference data type. In other words, it means that objects don't store the value, but they contain a reference to the location in memory where the actual values are stored.

Now, as we mentioned above, each object has its properties and methods. Lets deep dive further to understand these concepts.

Object Properties

The variables which hold the actual values inside an object are object properties. These variables can be of any of the primitive data types or maybe another object as well. JavaScript has provided the following syntax for adding a new property to an object:

Syntax - Set properties of an object:

objectName.objectProperty = propertyValue;  
or  
objectName[objectProperty] = propertyValue;

Similarly, JavaScript has provided the following syntax to read a property from an object.

Syntax - Get properties from an object:

var value = objectName.objectProperty;  
or  
var value = objectName[objectProperty];

So, dot(.) or square-bracket([]) operator allows accessing the properties of the object.

Object Methods

Methods are actions that can perform on objects. The user can create different methods for the various kind of functionalities that the object expects to provide. JavaScript provides the following syntax to invoke an object's method:

Syntax - Invoke method of an object:

objectName.methodName();

Note: Only the dot(.) operator can be used to invoke any method of an object.

Now that we have understood the internals of the object let's understand further how to create these objects.

How to create JavaScript Objects?

In JavaScript, all the objects, be it user-defined or built-in, are descendants of an object called Object. JavaScript provides the following ways to create an object:

  • Using Object literal.
  • Using Object Constructor (new keyword with Object).
  • Procedure to use Constructors (new keyword with functions).
  • Using Constructors (new keyword with class).
  • Procedure to use Prototypes (Object.create() method).

Using Object literal:

The object literal is the simplest way of creating objects in JavaScript. It uses the { } brackets to define a set of key-value pairs in { }, where the key would be property or method name, and value will be the value of the property or the function. We can use comma ( , ) to separate multiple key-value pairs. Moreover, its syntax will look like below:

Syntax - Creating an object using the "object literal" method:

var objectName = { variable1:value1, variable2:value2, variable3:value3 …….. variableN:valueN}

Let's understand these details using the following example, where we are creating an object which has both properties and methods:

<html>

	<body>
		Demonstrating Object creation using "Object literal" way in javascript </br>
    	<script type="text/javascript">
    		
    		// Declare an object
    		var obj = { 
    					// Declare properties of the Object
    					var1: "Tools",
    					var2: "QA",
    					var3: "JavaScript",

    					//Declare method of the object
    					displayInput:function () 
    					{                
    						document.write("Print values in function : ", this.var1 + " " + this.var2 + " " + this.var3);
    					}

    				} 

    		document.write("Access values using [] notation : ");
    		document.write(obj["var1"] + " " + obj["var2"] + " " + obj["var3"] + "</br>");

    		document.write("Access values using dot(.) notation : ");
    		document.write(obj.var1 + " " + obj.var2 + " " + obj.var3 + "</br>");

    		// Invoke the function.
    		obj.displayInput();

    	</script>
	</body>

</html>

Save the file with name objectCreatingUsingObjectLiteral.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 Javascript Objects - creation using Object Literal method

As is evident from the above code snippet and screenshot, the object is declared and initialized directly using the curly brackets ( {}). The properties of the object can be accessed outside the object, using the dot( . ) and square-bracket ([] ) operators, and the object properties can be accessed within the object methods using the "this" operator.

Note: We will discuss the details of "this" operator in future articles.

Using Object Constructor (new keyword with Object):

As we discussed above that,  in JavaScript, all the objects are descendants of an object called Object. So, the other way JavaScript provides to create an object is by using the new keyword with Object, or we can say invoking constructor of Object. After the creation of the object, the dot (.) or square-bracket ([] ) operators create the methods. Additionally, its syntax will look like below:

Syntax: Creating an object using the "Object constructor" method:

var objectName = new Object();
objectName.variableName = value;

Let's understand these details by re-writing the above program and creating the object using "Object constructor".

<html>

	<body>
		Demonstrating Object creation using "Object constructor" way in javascript </br>
    	<script type="text/javascript">
    		
    		// Declare an object
    		var obj = Object();
    		
    		// Declare and initialize properties of the Object
    		obj.var1 = "Tools",
    		obj.var2 = "QA",
    		obj.var3 = "JavaScript",

    		//Declare method of the object
    		obj.displayInput = function () 
    		{                
    			document.write("Print values in function : ", this.var1 + " " + this.var2 + " " + this.var3);
    		}

    				

    		document.write("Access values using [] notation : ");
    		document.write(obj["var1"] + " " + obj["var2"] + " " + obj["var3"] + "</br>");

    		document.write("Access values using dot(.) notation : ");
    		document.write(obj.var1 + " " + obj.var2 + " " + obj.var3 + "</br>");

    		// Invoke the function.
    		obj.displayInput();

    	</script>
	</body>

</html>

Save the file with name objectCreatingUsingObjectConstructor.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 Javascript Object creation using Object Constructor

As is clear from the above code snippet and screenshot, the object can declare by calling the constructor of "Object" and the properties and methods can be associated with the object using equal (=) operator.

Using Constructors (new keyword with functions):

JavaScript provides a way, using which we can use the "new" keyword with a function to create a new object. Using the "new" keyword before the function internally converts it to a constructor. Moreover, its syntax will look like below:

Syntax: Creating an object using the "function constructor" method:

let objectName = new functionName(functionParameters);

Let's understand these details by re-writing the above program and creating the object using "a new operator with the function".

<html>

	<body>
		Demonstrating Object creation using "new Operator with Function" way in javascript </br>
    	<script type="text/javascript">
    		

    		//Declare a function
    		function displayInput(param1, param2) 
    		{                
    			this.param1 = param1;
    			this.param2 = param2;
    		}

    				
    		// Create object using function
    		let display = new displayInput("Tools","QA");

    		document.write("Value for param1: ", display.param1,"</br>");
    		document.write("Value for param2: ", display.param2);

    	</script>
	</body>

</html>

Save the file with name objectCreatingWithnewOpeartoWithFunction.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 Creating javascript Object with new with Function

Using Constructors (new keyword with class)

While declaring a class, the user can specify a particular method named "constructor()", which can initialize the properties of the object. The only restriction is that JavaScript allows only one method with the name constructor(). Its syntax will look like below:

Syntax: Creating an object using the "class constructor" method:

let objectName = new className();

Let's understand, with the help of following code snippet, how to define a class and create an object using the "new" operator.

<html>

	<body>
		Demonstrating Object creation using "new Operator with class" way in javascript </br>
    	<script type="text/javascript">
    		

    		class displayClass {

    			constructor(param1, param2) 
    			{ 
        			this.param1 = param1;
    				this.param2 = param2; 
    			} 
			} 

    				
    		// Create object using classs
    		let display = new displayClass("Tools","QA");

    		document.write("Value for param1: ", display.param1,"</br>");
    		document.write("Value for param2: ", display.param2);

    	</script>
	</body>

</html>

Save the file with name objectCreatingWithnewOperatorWithClass.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 Creating object with new operator with class

As is evident from the above code snippet and screenshot, the user can invoke the constructor() method of the class by invoking the class name with the new operator, which in turn will return an object of that class.

Using Prototypes (Object.create() method):

Another way to create objects involves using prototypes. Moreover, its syntax will look like below:

Syntax: Creating an object using the "Object.create()" method:

let obj = Object.create(prototype_object, propertiesObject)
          // the second propertiesObject argument is optional

Let's understand, with the help of following code snippet, how to create an object using the "Object.create()" method:

<html>

	<body>
		Demonstrating Object creation using "new Operator with prototype" way in javascript </br>
    	<script type="text/javascript">
    		

    		let displayVariable = { 
    			param1: "Tools",
    			param2: "QA"
			} 

    				
    		// Create object using prototype
    		let display = Object.create(displayVariable);

    		document.write("Value for param1: ", display.param1,"</br>");
    		document.write("Value for param2: ", display.param2);

    	</script>
	</body>

</html>

Save the file with name objectCreatingWithPrototypes.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 Create object using prototypes

What are the methods provided by JavaScript Objects:

The JavaScript Object provides multiple methods that can be very handy for a programmer. Few important ones are:

  • hasOwnProperty()
  • keys()
  • getOwnPropertyDescriptor()
  • defineProperty()

Let's discuss all of these methods in detail with examples:

hasOwnProperty()

This function returns a boolean value and checks given input exist as a property in the object. Additionally, its syntax will look like below:

Syntax:

var obj = new Object();
obj.hasOwnProperty(variableName);

Let's understand the usage of function hasOwnProperty() with the help of following code snippet:

<html>

	<body>
		Demonstrating hasOwnProperty() method of Object in javascript </br>
    	<script type="text/javascript">
    		var objectName = new Object();
    		objectName.val1 = "Tools";
    		objectName.val2 = "QA";
    		objectName["val3"] = "Tutorials";
    
    		objectName.getData = function()
    		{
    		 	return this.val1 + " " + this.val2 + " " + this.val3;
    		}

    		// Validate properties of the objectss
    		document.write("Does val1 property exist in object: -- ",objectName.hasOwnProperty("val1"),"</br>");
    		document.write("Does val5 property exist in object: -- ",objectName.hasOwnProperty("val5"),"</br>");
    		document.write("Does getData property exist in object: -- ",objectName.hasOwnProperty("getData"),"</br>");
    	</script>
	</body>

</html>

Save the file with the name hasOwnProperty.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 hasOwnProperty of object

As is evident from the above screenshot, not only the properties but functions are also the properties of the object, and the method hasOwnProperty() returns true for functions as well.

keys()

This function returns all the variables and methods available in the given object. Additionally, its syntax will look like below:

Syntax:

Object.keys(objectName);

Let's understand the usage of function keys() with the help of following code snippet:

<html>

	<body>
		Demonstrating keys() method of Object in javascript </br>
    	<script type="text/javascript">
    		var objectName = new Object();
    		objectName.val1 = "Tools";
    		objectName.val2 = "QA";
    		objectName["val3"] = "Tutorials";
    
    		objectName.getData = function()
    		{
    		 	return this.val1 + " " + this.val2 + " " + this.val3;
    		}

    		// Validate properties of the objectss
    		document.write("Print Keys of the object: -- ");
    		document.write(Object.keys(objectName));
    	</script>
	</body>

</html>

Save the file with name objectKeys.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 Object keys method

getOwnPropertyDescriptor()

This method returns a "property descriptor" for the specified property of the given object. A "property descriptor" is an object that describes the attributes and value of a property.  A property descriptor generally has the following structure:

{
    value:        /* any JavaScript value */,
    writable:     /* true or false */,
    enumerable:   /* true or false */,
    configurable: /* true or false */
}

Where,

  • value: Actual value of the variable. By default, the value will be undefined.
  • writabletrue if the value of the variable will get change with the help of assignment operators. By default, the value will be false.
  • enumerable: true if this property will show up during enumeration of the corresponding object. By default, the value will be false.
  • configurable: true if the type of this property descriptor may change and if the property may delete from the corresponding object. By default will be false.

Its syntax will look like below:

Syntax:

Object.getOwnPropertyDescriptor(objectName,propertyName);

Let's understand the usage of function getOwnPropertyDescriptor() with the help of following code snippet:

<html>
 
	<body>
		Demonstrating propertyDescriptor() method of Object in javascript </br>
    	<script type="text/javascript">
    		var objectName = new Object();

            //Assign one property in the Object
    		objectName.property1 = "Tools";
 
    		// Get the descriptors of the property
            var descriptions = Object.getOwnPropertyDescriptor(objectName,"property1");
 
    		// Print all the descriptors of the property
            for( index in descriptions)
    		{
    			document.write(index + " : " + descriptions[index] + "</br>");
    		}
 
    	</script>
	</body>
 
</html>

Save the file with name propertyDescriptor.html. After that, open it in any browser (Chrome, Firefox, or IE)It should show the output as:

 Property Descriptors in JavaScript

  • As is evident from the above screenshot, the propertyDescriptor() method returns the details of attributes for the given property of the object.
  • Also, we can see that even though we are not updating any descriptors of the given property, all the values are true. It is due to the reason that whenever we assign a value to a variable, all the descriptor values establish in a way that they provide complete control over that variable. Hence all these values of descriptors are internally stored as true.

defineProperty()

This method adds or edits the behavioral attributes of the property. Moreover, its syntax will look like below:

Syntax:

Object.defineProperty(objectName, propertyName, descriptor)

Let's understand the usage of function defineProperty() with the help of following code snippet:

<html>

	<body>
		Demonstrating defineProperty() method of Object in javascript </br>
    	<script type="text/javascript">
    		var objectName = new Object();
    		objectName.val1 = "Tools";
    		objectName.val2 = "QA";
    		objectName["val3"] = "Tutorials";
    
    		objectName.getData = function()
    		{
    		 	return this.val1 + " " + this.val2 + " " + this.val3;
    		}

    		var descriptions = Object.getOwnPropertyDescriptor(objectName,"val1");

    		document.write("Descriptor attributes of property val1 before editing</br>")
    		for( index in descriptions)
    		{
    			document.write(index + " : " + descriptions[index] + "</br>");
    		}

    		// Edit the property
    		Object.defineProperty(objectName,'val1',{writable:false});

    		var descriptions = Object.getOwnPropertyDescriptor(objectName,"val1");

    		document.write("Descriptor attributes of property val1 after editing</br>")
    		for( index in descriptions)
    		{
    			document.write(index + " : " + descriptions[index] + "</br>");
    		}

    	</script>
	</body>

</html>

Save the file with name defineProperty.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as:

object defineProperty method

As is evident from the above screenshot, the user can update the behavioral attributes of the property using the defineProperty() method.

Key Takeaways

  • Objects are the standalone entities that hold specific properties and methods.
  • Moreover, the Objects in JavaScript can be created either by directly assigning the literals, using constructors of objects, functions or class, and using prototype method Object.create().
  • In addition to the above, each object in JavaScript supports specific methods such as keys(), defineProperty(), etc. which can access/manipulate particular attributes of the object.

To conclude, let's now move to the next article to understand some of the advanced features provided by JavaScript, such as Scheduling Tasks in JavaScript.

Math Object in JavaScript
Math Object in JavaScript
Previous Article
What is JavaScript Timeout?
What is JavaScript Timeout?
Next Article

Similar Articles

Feedback