Objective Reasoning – The Basic Javascript Object

What is an Object?

In Javascript an object is simply a container or store of properties that are related to what the object is modeling. These properties can be primitive data types, other objects or functions. Here’s an example of an empty object with no properties:

const furBearingTrout = {};

I’ve used object literal notation which is doing just what it sounds like – literally writing out the notation of an object. We do this using curly braces {}.

How to create properties

When we want to set a property on our object we can do it one of two ways:
1. Use bracket notation where we state the object name along with a property name in brackets and then assign a value using the equal sign:

furBearingTrout[“name”] = ‘Alpino-Pelted’;
furBearingTrout[“url”] = 'http://www.furbearingtrout.com/fish2.html';

2. Use dot notation where we state the object name followed by a dot followed by the property name we want to use and then assign a value using the equal sign:

furBearingTrout.name = ‘Alpino-Pelted’;
furBearingTrout.url= 'http://www.furbearingtrout.com/fish2.html';

I could have created our object with properties already assigned. Note that properties are written as name:value pairs separated by commas.

const furBearingTrout = { 
  name: ‘Alpino-Pelted’, 
  url: 'http://www.furbearingtrout.com/fish2.html'
}

How to access properties

Once we have properties we can access them using the same two methods we used to set them just without the equal signs that assign values.

console.log(furBearingTrout.name); //outputs ‘Alpino-Pelted’
console.log(furBearingTrout[‘url’]); //outputs 'http://www.furbearingtrout.com/fish2.html'

We can also create objects using the constructor method (new Object) or the Object.create() method but for this article we’ll stick to the literal notation for its simplicity and visual aid.

Functions in objects are methods

When the property is a function we call it a method. Methods do something with the data stored in the object. Imagine we had the following properties:

const furBearingTrout = {
  name: ‘Alpino-Pelted’,
  url: 'http://www.furbearingtrout.com/fish2.html',
  view: function () {
    console.log(`View the ${this.name} trout at ${this.url`;)
    }
}

You call a method by accessing the property name it’s associated with followed by parentheses.

furBearingTrout.view(); //ouputs ‘View the Alpino-Pelted trout at http://www.furbearingtrout.com/fish2.html

Why do I use ‘this’ ?

The ‘this’ keyword simply references the very object it’s inside of. So this.name is the same as saying neighbor.name. Outside of the object we would refer to furBearingTrout.name but inside the object we refer to this.name.

There’s a lot more to objects than what I’ve written here. But if you understand these basics you’ll already be able to model some fairly complex real world data and be able to manipulate it.