Open In App

How to read properties of an Object in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

Objects in JavaScript, it is the most important data type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive data-types all store a single value each (depending on their types).

In this article, we will see How can we read the properties of an object in JavaScript. There are different ways to call the properties of objects in Javascript.

Dot property accessor: In this, we use a dot property accessor to access the property of the object, the property must be a valid JavaScript identifier. 

Syntax:

ObjectName.propertyName

Example:

Javascript




<script>
    var obj={
        name : "Mohan Jain",
        age : 21,
        address : "Bhopal"
    };
      
    var name=obj.name;
    console.log(name); 
</script>


Output:

Mohan Jain

Using square brackets: In this, we use a square bracket to access the property of the object. It is the same as accessing the elements of an array using the square bracket.

Syntax:

ObjectName[propertyName]

Example:

Javascript




<script>
    var obj={
        name : "Mohan Jain",
        age : 21,
        address : "Bhopal"
    };
      
    var name=obj[name];
    console.log(name);  
</script>


Output:

Mohan Jain

Object destructuring: In this, we read a property and assign its value to a variable without duplicating the property name. It is similar to array destructuring except that instead of values being pulled out of an array. The properties (or keys) and their corresponding values can be pulled out from an object.

Syntax:

var { propertyName } = ObjectName

Example:

Javascript




<script>
    var obj={
        name : "Mohan Jain",
        age : 21,
        address : "Bhopal"
    };
      
      
    var { name } = obj;
    console.log(name);  
</script>


Output:

Mohan Jain

Accessing the property of Object using jQuery: Make sure you have jquery installed. We can use the jQuery library function to access the properties of Object. jquery.each() method is used to traverse and access the properties of the object.

Example:

Javascript




<script>
    const jsdom = require('jsdom');
    const dom = new jsdom.JSDOM("");
    const jquery = require('jquery')(dom.window);
      
    var obj={
        name : "Mohan Jain",
        age : 21,
        address : "Bhopal"
    };
      
    jquery.each(obj, function(key, element) {
        console.log('key: ' + key + '   ' + 'value: ' + element);
    });
</script>


Output:



Last Updated : 21 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads