Accessors

Technically, property accessors is the correct term here. I find that a little confusing because we discuss objects in javascript as having properties and methods. Well, as it turns out, methods are actually properties themselves. The distinction is that methods are properties the values of which are defined by a function. They’re still properties. This is important as you’ll see in the expamples below. The following post will address the ways you can access any “public” part of an object (properties and methods) in JavaScript. There are only two ways, and officially they are called property accessors.

An object is a collection of properties, and a property is an association between a name and a value. A property’s value can be a function, in which case the property is known as a method.
MDN


There are two ways to access the properties of an object. The first is “dot notation.” Let’s initialize a variable with an object literal and then access its properties with dot notation.

var myObject = {

  // 1st property
  name: 'Clark Griswold',

  // 2nd property
  wife: 'Ellen Griswold',

  // 3rd property (also happens to be a method)
  getName: function() {
    return this.name;
  }

};

// Access the properties

myObject.name        // Clark Griswold
myObject.wife        // Ellen Griswold
myObject.getName     // [Function]

Ok, so that’s pretty straight forward. Dot notation is the more common way to access object properties. It is the preferred method, assuming you know what properties you need access to. Note the return of [Function] from myObect.getName. Since we didn’t invoke the function, we simply get a reference to it. You can pass functions around like any other variable. Remember, they won’t be invoked unless we call them with opening and closing parenthesis, like this…

var name = myObject.getName;

name      // [Function]
name()    // Clark Griswold

The second way to access an object’s properties is with “bracket notation.” It’s also pretty simple.

var myObject = {

  // 1st property
  name: 'Cousin Eddie',

  // 2nd property
  wife: 'Catherine',

  // 3rd property (also happens to be a method)
  getName: function() {
    return this.name;
  }

};

// Get the properties

myObject['name']        // Cousin Eddie
myObject['wife']        // Catherine
myObject['getName']     // [Function]

As you can see, this requires just a bit more typing and doesn’t read quite as nicely as dot notation (in my opinion), BUT this is more powerful. Bracket notation is what’s known as a “computed property accessor.” This means that whatever value is within the brackets is computed (or evaluated), before it accesses the object. So we can use variables or other expressions to dynamically access an object’s properties. This is not possible with dot notation.

let myObject = {

  method1: function() {
    return 'method 1!';
  },

  method2: function() {
    return 'method 2!';
  }
};

let preferredMethod = 'method1';

myObject[preferredMethod]();    // method1!

preferredMethod = 'method2';

myObject[preferredMethod]();    // method2!

myObject.preferredMethod();     // TypeError <- Dot syntax does not compute

You can also set properties with variables/expressions.

myObject[ 'clark' + ' says' ] = 'If I woke up tomorrow with my head sewn to the carpet, I wouldn\'t be more surprised than I am now.';

myObject['clark says'] // If I woke up tomorrow with my head sewn to the...

Okay, that’s pretty cool. Knowing this, if you wanted to get all the property values of an object, you might write a function like this…

function getAllPropertiesOf(anObject) { // <- pass in an object reference

  let propertyNames = Object.keys(anObject); // <- get all of the object's own properties

  propertyNames.forEach( function(property) {
    console.log( anObject[property].toString() ); // <- for each of the properties, log its value toString
  });
}

And call it like so…

let someObject = {
  prop1: 'Some value',
  prop2: 'Another value',
  prop3: function() {
    // Do work
  }
};

getAllPropertiesOf(someObject);

// Some value
// Another value
// function () { // Do work }

You could modify this and throw a callback into the mix…

function getAllPropertiesOf(anObject, callback) {

  let propertyNames = Object.keys(anObject);

  propertyNames.forEach(function(propertyName) {

    // This time, we'll invoke our callback with two arguments
    callback( propertyName, anObject[propertyName] ); // <- second argument uses bracket notation to access the value of the property
  });
}

If you’re confused by the callback function, I got you covered—read this. However, callbacks aren’t the focus of this. This is about computed accessors. They’re neat, you guys!

let family = {
  surname: '',
  members: {}
};

// Create a family object
let griswolds = Object.create(family);

// Populate the family 'members' object
griswolds.members = {
  parents: ['Clark', 'Ellen'],
  children: ['Audrey', 'Russ'],
  cousins: ['Eddie', 'Catherine']
};

getAllPropertiesOf(griswolds.members, function(propertyName, propertyValue) {
  console.log( propertyName, propertyValue );
});

// parents ["Clark", "Ellen"]
// children ["Audrey", "Russ"]
// cousins ["Eddie", "Catherine"]

If you’re newer to JavaScript, the utility of accessing objects with bracket notation might not be immediately evident. But remember computed accessors as they will most certainly be of use, if not now, at some point. I guarantee it.