Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Objects

Objects are representations of real world entities like people, animals, cars etc. Objects allow us to group related variables together and if needed even create functions that will perform more complex actions. JavaScript has built-in objects and also allows us to create your own custom objects.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-objects

Open the directory javascript-objects in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • objects.js - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-objects
-objects.js

JavaScript Built-in Objects

From the begging of these practical lessons, we have been working with console.log to print out things to the terminal. console is a built-in object that has a method called log which accepts a string then prints it out to the terminal. An object's method is simply a function that performs a specific task.

The following syntax shows how to access an object's methods.

object_name.method_name([params]);

HERE,

  • object_name specifies the object name like console, person, animal etc.
  • .method_name() specifies the object method to be accessed. The opening and closing brackets are mandatory when calling methods.
  • ([params]) specifies the parameters to be passed to the method. Some methods do not accept parameters. Other can accept single or multiple parameters depending on what the method does. Multiple parameters are separated using commas.

The following example shows how to use the console object to print out something in the terminal.

console.log('calling log method of console object with string paramater');

Executing the above code produces the following results.

calling log method of console object with string paramater

JavaScript Custom Objects

Let's now create a custom object. Let's suppose that we are working on an application that will be dealing with cars. The car data we are interested in is the make, type and printing out a simple description of the car. We can do it like so.

Open the file objects.js and add the following code

let car = {
    'make':'Toyota',
    'type':'Vitz',
    'toString' : function(){
        return 'The car make is ' + car.make + ' the type is ' + car.type;
    }
};

console.log(car.toString());

HERE,

  • let car = {...} defines an object variable called car. The object declaration is done is curly brackets {}
  • 'make':'Toyota', defines an object attribute make and assigns the value Toyota to it. Notice how the attribute is defined by pairing a key and a value separated by a full colon :.
  • 'type':'Vitz', defines a type attribute with the value of Vitz.
  • 'toString' : function(){...} defines a function toString that will print a simple description of the car object. The function uses the values of the car object attributes car.make and car.type.
  • console.log(car.toString()); prints out the description of the car in the console. Notice the open and closing brackets () when calling the method.

Open the terminal and run the following command

node objects.js

The above code should produce the following results

The car make is Toyota the type is Vitz

Accessing an object's attributes

We basically have two ways of accessing the attributes of an object. We can using the dot or bracket notation. The dot notation is the most commonly used one. The bracket notation comes in handle when you do not know what attribute of the object should be selected during design time. For example, you can present a user with options in the user interface and then depending on what property the user selects, you then access that attribute.

Dot Notation

The following example shows how to access an object's property using the dot notation.

let animal = {
    'type':'Dog',
    'color':'Brown'
};

console.log(animal.color);

HERE,

  • let animal = {...} defines an animal object with attributes type and color
  • console.log(animal.color); access the color attribute using the dot notation and prints out the value in the console. Notice we do not include the open and closing brackets () when accessing object attributes.

Executing the above code produces the following results

Brown

Bracket Notation

The following example shows how to access an object's attribute using the bracket notation.

let person = {
    name: 'James Bond',
    occupation: 'Spy'
};

console.log(person['occupation']);

HERE,

  • let person = {...} define a person object with attributes name, and occupation
  • console.log(person['occupation']); accesses the occupation attribute using the bracket notation.

Executing the above code produces the following results

Spy

Summary

JavaScript objects are representations of real world entities such as people, buildings, animals etc. Objects can contain variables and functions. variables simply hold values where as functions are capable of far much more complex operations and returning values if necessary.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript Primitive Types

JavaScript Arrays

Leave A Reply