Object Literals | JavaScript & Object Oriented Programming | Part 3

In the Previous Tutorial, we setup our development environment with the following setup –

  • Google Chrome & its Developer Tool
  • Visual Studio Code (VS Code)
  • Live Server (VS Code extension)
  • Writing some boilerplate HTML and JavaScript Code
  • Running the app and verifying Hello World

In this tutorial we’ll learn the following –

  • What is an Object?
  • Different ways to create objects
  • What is an Object Literal?
  • How to create object by using Object Literal?
  • How to access object properties?
  • How to declare and call methods?

In all the ES5 tutorials, I’ll be using var to declare variables just to align with the ES5 syntax. But you should never use var and use let or const to declare variables. Read this tutorial to know why?

What is an object?

JavaScript gets along with objects very well. An object in JavaScript is a collection of key-value pairs. The key can be a String or Symbol. I’ll discuss Symbols later in this tutorial. The value can be anything – primitives like number, string etc or another object.

The beauty with JavaScript is that it considers functions to be an object. So you can have a function as the value of a key of an object.

The keys with primitive values/objects are called properties and one with function values are called methods. Properties are supposed to hold object data while methods are supposed to contain business logic to work with the data. Together they are called members of an object.

Objects are the basis of implementing Encapsulation in JavaScript.

If you remember, we discussed Encapsulation in This Tutorial?

Getting Confused? Let’s see things in action.

Different ways to create an object in JavaScript

What is an Object Literal in JavaScript?

You declare an object literal by using this symbol – {}

var car = {};

The above statement creates an empty object in memory and the variable car refers that object. Please note that this object does not have any key-value pair. So essentially this object has no members, neither properties nor methods.

To create an object with some properties we can pass it the key-value pairs – key: value. Each key-value pair is separated by a comma.

Head over to the VSCode, go to the myjs.js file and write the below code –

var car = {
  make: 'Volkswagen',
  model: 'Golf',
  'selected gear': 1
};

Did you notice?

We wrapped the property selected gear with quotes. If any property has space in its name, you MUST warp it with quotes like you do with strings.

How to access object properties?

You can access the object properties following one of the two notations – Object.Key or Object[‘Key’]. The dot notation is more popular.

So at the end of myjs.js file write the following code –

console.log('Make: ' + car.make);
console.log('Model: ' + car['model']);
console.log('Selected gear: ' + car['selected gear']);

Did you notice?

If the key has spaces, you MUST access it by using following syntax – Object[‘Property’]. You CANNOT access it with dot notation.

It is a good practice to write property names using camelCase. So let’s rename our ‘selected gear’ property as selectedGear. We can omit the single-quote now. Also, accessing property using dot notation is preferred.

Updated code in myjs.js

var car = {
  make: 'Volkswagen',
  model: 'Golf',
  selectedGear: 1
};

console.log('Make: ' + car.make);
console.log('Model: ' + car.model);
console.log('Selected gear: ' + car.selectedGear);

Save the code and if Live Server is running it should display the following in the browser console –

Make: Volkswagen
Model: Golf
Selected gear: 1

Do you Know?

You can also write all your JavaScript code in the browser console.

Lets Experiment

Open Chrome Developer Tools and go to the Console tab. Type in the object name and hit enter. Expand the value and notice if you can see the members of that object –

Some more Experiment

Create a new object in the browser console with couple of properties. Press enter and in the next line try accessing that property. See if it prints the value of that property.

Try playing with the object more. See if you can change the ratings.

Hey, what if I want to change the gear? How to update the object property?

The same way as you access the object property, you can update its value. Go to the chrome console and run the following three commands one by one-

car.selectedGear = 2
car.selectedGear

The console should display the updated gear – 2

How to declare and call methods?

So far we have added attributes/properties to the car object. But we also want the car to run. For this we also need to add a run() method to the object. This is how our updated code would look like after adding the run() method.

var car = {
  make: 'Volkswagon',
  model: 'Golf',
  selectedGear: 1,

  run: function(){
    console.log('Car is running... Gear ' + this.selectedGear);
  }
};

Did you Notice?

You can access object properties in methods by using this.property-name syntax. Keyword this in JavaScript refers to the current object invoking the code. In our example above this.selectedGear refers to the selectedGear property of the current object that called the run() method.

But who called the run() method? I do not see any message in the browser console.

Good question! We have just created a car that has some attributes like make, model and a method run(). We need to call this method explicitly. The car is not running yet.

How to call the method of an object?

Just like you access object’s property by using dot notation, you can call its method –

car.run()

Updated myjs.js

var car = {
  make: 'Volkswagon',
  model: 'Golf',
  selectedGear: 1,

  run: function(){
    console.log('Car is running... Gear ' + this.selectedGear);
  }
};

//Call method
car.run();

Go to the browser console and verify if it is running.

Summary

  • What is an Object?
  • Different ways to create objects
  • What is an Object Literal?
  • How to create object by using Object Literal
  • How to access object properties?
  • How to declare and call methods?

How was it? Overwhelming??? If you think you have learned everything about objects check out the Next Tutorial.

Leave a Reply