Understanding  the ` This`  Keyword  in  Javascript

Understanding the ` This` Keyword in Javascript

The this keyword behaves differently in a programming language but in this article, we're going to have a closer look at the this keyword in JavaScript this is one of those features that confused me when I was learning javascript.

What is the this keyword?

this keyword references to the object that is executing the current function, it’s a javascript built-in keyword that can be used in different forms for example :

  • if that function is part of an object, we call the function and method
  • if that function is a method in an object, the this keyword references that object itself
  • if that function is a regular function which means it's not part of an object, the this keyword refers to the global object which is the window object
  • In strict mode, the this keyword is undefined

    Source: stackoverflow

Note: this keyword is not a variable, you can't change the value of the this keyword. It is a keyword that refers to an object.

The question is, what is the value of this almost everyone who has ever written javascript has at some point run into an error.

  • The this keyword refers to the object that is executing the current function.

Here is an example :

const person = {
  name: 'David Igheose',
  type: 'frontend developer',

  career: function () {
  console.log(`My name is ${this.name} am a ${this.type}`)
  }
}

person.career()

// Output:
// My name is David Igheose am a frontend developer

Why the this keyword?

We know the this keyword is not a variable, it refers to the current object, so why do we have to use the this keyword to refer to an item in an object, when we can just call the item itself, here is a code example that explains why we use the this keyword.

So we have two object data called person one and person two :

// person one 
const person1 = {
  name: 'John don',
  type: 'Blockchain developer',
}

// person two 
const person2 = {
  name: 'David Igheose',
  type: 'frontend developer',
}

in the above objects, we are adding a function to the objects which looks like this:

// persona one
const person1 = {
  name: 'John don',
  type: 'Blockchain developer',

  career: function () {
  console.log(`My name is ${person1.name} am a ${person1.type}`)
  }
}
person1.career()
// Output:
// My name is John don am a Blockchain developer


// person two
const person2 = {
  name: 'David Igheose',
  type: 'frontend developer',

  career: function () {
  console.log(`My name is ${person2.name} am a ${person2.type}`)
  }
}

person2.career()

// Output:
// My name is David Igheose am a frontend developer

from the code example, we can see that the this keyword is not used, we are just using the object name to refer to the item inside it, for example :

// person one
career: function () {
  console.log(`My name is ${person1.name} am a ${person1.type}`)
 }

// person two
career: function () {
  console.log(`My name is ${person2.name} am a ${person2.type}`)
  }

the problem with this method is that using the object name to refer to an item can cause a code error in the sense that if one decides to refer to the person1 object inside person2 object, for example :

// persona one
const person1 = {
  name: 'John don',
  type: 'Blockchain developer',

  career: function () {
  console.log(`My name is ${person1.name} am a ${person1.type}`)
  }
}

person1.career()

// Output:
// My name is John don am a Blockchain developer

// person two
const person2 = {
  name: 'David Igheose',
  type: 'frontend developer',

  career: function () {
  console.log(`My name is ${person1.name} am a ${person1.type}`)
  }
}

person2.career()

// Output:
// My name is John don am a Blockchain developer

the output of the two object method calls we be the same, this is why when referring to the object that is executing the current function we need to use the keyword this.

“This” keyword in strict mode

Outside any object, this in strict mode is always undefined. Notice I mentioned strict mode. If strict mode is disabled (the default state if you don't explicitly add 'use strict' on top of your file ), you are in the so-called sloppy mode, and this - unless some specific cases mentioned here below - has the value of the global object. Which means a window in a browser context. Source: flaviocopes

“This” keyword inside an Arrow function

When using the this keyword inside an arrow function, the arrow function blocks the this keyword from referring which means rather than printing the value, the referred item becomes undefined. for example :

// person object
const person = {
  name: 'David Igheose',
  type: 'frontend developer',

  career: ()  => {
  console.log(`My name is ${this.name} am a ${this.type}`)
  }
}

person.career()

// Output:
// My name is undefined am a undefined

for functions, we have three types for them which are :

  • Function Declaration - automatically bound to the object.
  • Function Expression - automatically bound to the object.
  • Arrow Function - it's lexically bound.

Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions. Source: Ashutosh Verma

The call() or apply()

call and apply are very similar—they invoke a function with a specified this context, and optional arguments. The only difference between call and apply is that call requires the arguments to be passed in one by one, and apply takes the arguments as an array. Source: Tania Rascia

In this example, we'll create an object, and create a function that references this but has no this context.

// person object
const person = {
  name: 'David Igheose',
  type: 'frontend developer',
}


const career = function(props) {
  console.log(`My name is ${this.name} am a ${this.type} and a ${props}`)
}

career.call(person, "technical writer")

// Output:
// My name is David Igheose am a frontend developer and a technical writer

career.apply(person, ["technical writer"])
// Output:
// My name is David Igheose am a frontend developer and a technical writer

we can see the difference between the call() and apply() method, the call() method takes the arguments separately while the apply() method takes the arguments as an array.

What's next?

Now you know the basics of how the this keyword works. You know what it is, and why it can be useful. But nothing will convince you more than some hands-on experience.

Thank you for reading

Feel free to subscribe to my email newsletter and Connect with me