You don't know 'this' in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

The this keyword in JavaScript refers to the main object which it belongs to and it has different values depending on where it is used:

  • Inside a method or object this refers to the owner/current object.
  • Alone or inside a function it refers to the global object(window object in browsers).
const foo = {
    name: 'Rahul', 
    func: function() {
console.log(foo.func()); // 'Rahul'

Now let's see some examples with the arrow function and normal method

const foo = {
    name: 'RAHULISM', 
    arrowfunc: _ => `Welome to "${}"`, 
    fooMethod: function() {
        return `Welcome to "${}"`; 
console.log(foo.arrowFunc()); // Welcome to ""
console.log(foo.fooMethod()); // Welcome to RAHULISM

Here fooMethod() is a method inside the object so this refers to the current object, but for arrow function this always points to the closest function scope. Since foo is not a function so the this inside the arrowFunc() points to the global object (in browser window object).

Now let's try the same inside a function.

function foo () { = 'RAHULISM'; 
    const arrowFunc = _ => `Welcome to ${}`; 
    function normalFunc () { 
        return `Welcome to ${}`; 
    return { arrowFunc, normalFunc }; 
console.log(foo().arrowFunc()); // Welcome to RAHULISM
console.log(foo().normalFunc()); // Welcome to undefined
  • arrowFunc(): this points to the nearest function scope and so prints 'RAHULISM'.
  • normalFunc(): this points to the global object, which does not have the property 'name' and so prints undefined.

You should make use of this.

⚡Happy Coding | Thanks For Reading😎

No Comments Yet