Categories
JavaScript Programming

Advanced Javascript Objects Introduction

To myself…

Using this keyword

Suppose we have an object

const myDog = {
   breed: 'dalmatian',
   bark() {
      console.log('woof');
   },
   getBreed() {
      console.log(breed);
   }
}

When we run myDog.getBreed() we expect that we will see dalmatian in our console. However, in actual, we get an error ReferenceError: breed is not defined. Why is that?

The reference error surfaces because by default, an object method does not have visibility inside the calling object’s properties.

To indicate that we are referring to the calling object’s breed property, we need to use this as in

const myDog = {
   breed: 'dalmatian',
   bark() {
      console.log('woof');
   },
   getBreed() {
      console.log(this.breed);
   }
}

The this keyword references the calling object allowing us to access what’s inside the myDog object.

Now suppose we use an arrow function in our object method

const myDog = {
   breed: 'dalmatian',
   bark() {
      console.log('woof');
   },
   getBreed: () => {
      console.log(this.breed);
   }
}

Surprisingly, we will get undefined as the log. Why is this so?

Using an arrow function inherently binds this not to the calling object but to the global object. Currently, there’s no breed property in the global scope so the getBreed arrow function returns undefined.

What does this mean? It means we should avoid using arrow function when using this in a method.

Conveying privacy

In Javascript, only by naming convention we can make a property private using underscore prefix as in

const imAnObject = {
   _myPrivateProperty: 'i am private'
}

Creating factory functions

Just like a real world factory that manufactures copies of an item quickly and on a massive scale, a factory function is a function that returns an object and can be reused to make multiple object instances.

Why is this useful? With a factory function, we don’t need to create an object literal every time we need a new object. We can invoke the factory function with the necessary arguments to make an object for us!

Categories
JavaScript Programming

Undefined vs Null in JavaScript

To myself… May I help other fellow coders use undefined and null appropriately through this short article.

Variable declaration and initialisation

Before having a solid understanding of the differences between undefined and null, it’s important to know the steps in declaring and initialising a variable.

Declaring is giving the variable a name.

let catName;

Initialising is giving the variable a value

catName = "Felicia";

Combining these two statements, we have a variable that has been declared with a name catName and a value of Felicia

let catName; // declaration
catName = "Felicia"; // initialisation

Undefined

Technically speaking, undefined means lack of an assigned value.

You can think of undefined as the default value of variable when it has not been assigned a value.

Rephrased slightly, undefined means either (1) variable is not declared (2) variable is declared but no value is assigned to it.

Null

With null, it means variable is declared and the coder explicitly set the value to null.

Null can be used to mean that the value does exist but at this point it is not yet known. For example an online form with an age field. Setting the age variable with null value means we know that the person’s age exists but we don’t know it yet (since the person has not filled in the details yet).

Difference in data types

The undefined is in its own data type whereas null is an object. Pretty confusing but that’s how undefined and null are designed in JavaScript.

Something to think about

Typically, you can lose the context between the JavaScript language assigning the variable a value and you as a coder explicitly assigning the variable a value. Hence, if you need to assign an emptiness to the variable, null is used. If it’s the JavaScript to assign the value, you just need to declare the variable and it will have implicit default value of undefined.

Categories
JavaScript Object-Oriented Design Programming

JavaScript Class and Method

To myself… Even if you hate how JavaScript classes are designed, you must know the class context by heart to avoid encountering type error exceptions in your code.

Creating an object

Suppose we need a JavaScript program to log any dog name to the browser console. We can start off by creating a blueprint of a Dog using class keyword in ES6 like this:

class Dog {
  printName(name) {
    this.print(`My name is ${name}`)
  }

  print(text) {
    console.log(text)
  }
}

const myDog = Dog()
myDog.printName('Tyler') // error here

What’s interesting in this piece of code is that the printName context changes and expectations are thrown.

Uncaught TypeError: Cannot read property 'print' of undefined

This is because the methods inside a class are bound to the class prototype and NOT to the class instance.

Binding a method to the class instance

So what we can do to make our code work?

One way is to bind the method to the class instance explicitly using bind keyword in the constructor by hand.

class Dog {
  constructor () {
    this.printName.bind(this)
  }
}

There are other ways to attach the method to the object instance but for now, we’ll stick to this since it’s the easiest and straight forward solution.