DEV Community

Guru
Guru

Posted on

Scary Keyword In JavaScript

Alt Text

Yes i call this key word in JavaScript the most scariest keyword because it kept confusing me for long time even though i was already a JavaScript developer, i encountered this key word when i started my journey as a React developer, let us see how we can make it easier to understand.

Impoorrtant : this keyword behaves differently when we use it in function and and object methods.

let us create a simple file called thisKeyWord.js and add the following line of code

console.log(this) // {}
Enter fullscreen mode Exit fullscreen mode

Inside the regular functions

let us create a function and do the following

function myFunction(){
    console.log(this);
}

myFunction();
Enter fullscreen mode Exit fullscreen mode

in the console we can see that its an global window object
Alt Text

Inside the object methods

let us add the following code in the file

let person = {
    name : "Guru",
    age : 29,
    gender : "male",
    getDetails() {
            console.log(this);
    }

};

person.getDetails();
Enter fullscreen mode Exit fullscreen mode

in the console we can see that its the object itself

Alt Text

Summary

  1. Inside the regular functions , this keyword is an global object
  2. Inside the object methods its the defined object itself

I have explained in my youtube video also , please like, share and subscribe to my youtube cahnnel if you like my content

Top comments (1)

Collapse
 
dmail profile image
Info Comment hidden by post author - thread only accessible via permalink
Damien Maillard

It's even scarier than that :D

Some comments have been hidden by the post's author - find out more