How many ways can a property of a JavaScript object be accessed?



 An object property can be accessed in two ways. One is .property and the other is [property].

Syntax-1

Object.property;

Syntax-2

Object["property"];

For better understanding, lets' look at the following example.

In the following example an object called 'person' is defined and its properties were accessed in a dot notation.

Example

Live Demo

<html> <body> <script> var person = {    firstname:"Ram",    lastname:"kumar",    age:50,    designation:"content developer" }; document.write(person.firstname + " " + "is in a role of" + " " + person.designation); </script> </body> </html>

Output

Ram is in a role of content developer

In the following example the properties of an object 'person' were accessed in bracket notation.

Example

Live Demo

<html> <body> <script> var person = {    firstname:"Ram",    lastname:"kumar",    age:50,    designation:"content developer" }; document.write(person['firstname']+ " " + "is in a role of" + " " + person['designation']); </script> </body> </html>

Output

Ram is in a role of content developer
Updated on: 2020-06-29T11:33:58+05:30

378 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements