Objects : The Basics

Objects : The Basics

Understanding what are objects and how to deal with them.

Introduction

Before getting into object oriented learning, first we need to understand that why do we have a paradigm, a means of organizing code. Suppose we have a thousand lines of code, we would not want it to run in a procedural manner, one command after another. We would want to organize it such that if we combine up all the data and functionalities associated with that data then we would not have to go hunt what functionality is applicable to this data, it will all be bundled up. Hence, it will be an easier way to develop and reason about, but the question is how might we bundle up our data? Here objects come to help us.

Out of eight data types in JavaScript, one is object, objects store data as keyed collection known as properties. A property is a "key : value" pair where, key is a string and a value can be anything. The properties are enclosed with in curly brackets {...} which makes it an object.

Creating an object in JavaScript

we must need to store our object somewhere so we will declare an identifier and assign an empty object to it. let's see how to do this.

const student = { };

This is how you create an object, but this student is an empty object right now so it is not very useful for us for now. let's update it and add some properties.

const student = { 
    name : "Bob",
    semester : 6,
    courses : ["Calculus" , "Physics" , "Statistics"],
};

We can see here, now our object has three different properties in the form of "key: value" pairs, separated with commas. An object like student is referred to as object literal.

Dot Notation

Now that we have created an object, how do we access the properties or the data we have stored? We will use dot notation. In dot notation, the object name which in our case is student acts as namespace it must be written first to access the data encapsulated in objects then a dot, then the item you want to access. Let's see the code.

student.name; 
student.semester;
student.courses[0];  // accesses courses property's element at 0th index which is "Calculus".

Sub-namespaces

it is possible that a property of an object is an object too, for example let's make name property an object having two properties firstName and lastName.

 const student = { 
    name : {
        firstName : "Bob",
        lastName : "Charles",
    },
    semester : 6,
    courses : ["Calculus" , "Physics" , "Statistics"],
};

How do we access firstName or lastName? to access these items you just need to chain the extra step onto the end with another dot.

student.name.firstName;

Bracket Notation

Another way of accessing object properties is bracket notation, it looks similar to how we access array elements let's see how it works.

student["semester"];
student["name"]["firstName"];

it is the same thing as we have seen in arrays but instead of array indices we are using property's key to access the associated values. This is the reason sometimes objects are called associative arrays. We can use bracket notations when keys are inaccessible using dot-notation for example keys having spaces or characters. let's see an example, in this example I have changed the keys for first and last names.

 const student = { 
    name : {
        "first name" : "Bob",
        "last-name" : "Charles",
    },
    semester : 6,
    courses : ["Calculus" , "Physics" , "Statistics"],
};

if we try to access it using dot notation we will get errors.

image.png

Here I tried to access it directly using dot notation, funnily it is considering hyphen as minus sign and hence results in NaN.

Then I tried to use it as a string which is obviously invalid. But it is valid if we use bracket notation. Same strategy will be valid for first name too.

Setting Object Properties

We have learnt how to access or get data in an object but how do we set or modify a property in an object? let's learn how.

student.semester = 7;
student.name["first name"] = "Bobby";

Now try accessing these values and you will get the updated ones.

student.semester;
student.name["first name"];

We can also add new properties to an object using this method. Let's see how can we do this.

student["roll number"] = "SE-15045";
student.gpa = 3.5;

Now try accessing student you will see two new properties "roll number" and gpa.

student["roll number"];
student.gpa;

Computed Property Names

If you need to use a computed expression value as the key name, this approach will be very useful. Let's see how to do this.

const suffix = "name";
student["first"+ suffix] = "Bob";
student["last"+ suffix] = "Charlie";

Now if we access them we will get the values of first and last names.

student["firstname"];
student["lastname"];

Setting Functions As Object Properties

We can also set functions as properties of objects and then call them using dot notation. Let's see how

student.sayHi = function (){
     console.log("Hello I am a student");
}

This function can be called like this and it will log on the console "Hello I am a student".

student.sayHi();

Hmm... 🤔 I think I have came across objects before in JavaScript

Since we have used dot notation in our examples, I am sure you might be thinking this is familiar if you have used methods for arrays like push, pop, shift etc. This is because Arrays are built-in sub-types of objects in JavaScript. There are other built in object sub-types are present in JavaScript too such as,

  • String
  • Number
  • Boolean
  • Object
  • Function
  • Array
  • Date
  • RegExp
  • Error

All of these are different from their respective primitive types but all of these have their properties and functionalities we use on daily basis.

What Have We Learnt So Far?

  • We have learnt that objects are a very useful to bundle up same kind of data and functionalities together.
  • How to make an object literal.
  • How to add properties in an object.
  • How to access object's properties using dot notation and bracket notation.
  • How to update properties.
  • How to add new properties.
  • How to make use of computed properties.
  • Setting functionalities in an object and how to call them.
  • Learnt about some built-in objects in JavaScript.