JavaScript Tutorials

Accessing Object Properties

There are two ways to access a property of an object:

  • Using square bracket notation, for example: hero[‘occupation’]
  • Using the dot notation, for example: hero.occupation

The dot notation is easier to read and write but it cannot always be used. The same rules apply as for quoting property names: if the name of the property is not a valid variable name, you cannot use the dot notation. Let’s take this object:

var hero = {
  breed: 'Turtle',
  occupation: 'Ninja'

Accessing a property with the dot notation:


Accessing a property with the bracket notation:


Accessing a non-existing property returns undefined:

'Hair color is ' + hero.hair_color;
//Hair color is undefined

Objects can contain any data, including other objects.

var book = {
  name: 'Catch-22',
  published: 1961,
  author: {
    firstname: 'Joseph',
    lastname: 'Heller'

To get to the firstname property of the object contained in the author property of the book object, you use:

Or using the square braces notation:


It works even if you mix both:['lastname']


One other case where you need square brackets is if the name of the property you need to access is not known beforehand. During runtime, it is dynamically stored in a variable:

var key = 'firstname';[key];

Looping through object properties

We can loop through the properties of an object to access them all at once. For this, we can use a for…in loop to iterate through the properties as follows:

var edupoly = {
   'course': 'ReactJS',
   'duration': '60 hours',
   'trainer': 'Praveen'

for(var key in edupoly){

//60 hours

Here, we are printing all the property values in the console using the for…in loop.

Note: In the for…in loop, we have to access the object properties using the square bracket notation only(not dot notation).


Create an object with two properties and print them in the console using dot notation and square bracket notation.
var phone = {
  'type': 'smartphone',
  'price': 25000
//dot notation

//square bracket notation

Create an object with a property that contains another object.

var user = {
  'name': 'Harry',
  'details': {
               'age': 35,
               'gender': 'male'

Create an object with a property that contains another object with age and gender properties and print the age and gender values in the console.

var user = {
  'name': 'Harry',
  'details': {
               'age': 35,
               'gender': 'male'

Create an object with a property that contains an array with four values and print the first value of the array in the console.

var sport = {
  'name': 'cricket',
  'players': ['Virat', 'Rohit', 'Shikhar', 'Dhoni']