Accessing Object's Properties

A property of an object can be accessed using two ways.

  • Using square bracket notation, for example hero['occupation']
  • Using the dot notation, for example hero.occupation

The dot notation is commonly used 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:

hero.breed;
"Turtle"

Accessing a property with the bracket notation:

hero['occupation'];
"Ninja"

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.

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

book.author.firstname

"Joseph"

Or using the square braces notation:

book['author']['lastname']
"Heller"

It works even if you mix both:

book.author['lastname']
"Heller"

book['author'].lastname
"Heller"

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';

book.author[key];
"Joseph"
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +