What is This keyword in JavaScript?

So, JavaScript introduce this keyword in es5 but some new things came into this keyword in es6 or es2015. It is a keyword to access members of objects. Ok! lets talk about one examples to understand this properly…

JavaScript object Exemple -1

Here, you can see I make a object named person and I set firstName, secondName , age and to access that I use this keyword and after that I use a JavaScript method to print birth year of this person. Ok! just check what is this code gives output.

Ram Agarwal age is 1969

Some this keywords facts:-

  • When you set a arrow function instead of making a normal function the this keyword represents lexical this. And now what is lexical scope:

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

Example of this is

Arrow functions are special: they don’t have their “own” this. If we reference this from such a function, it’s taken from the outer “normal” function.

For instance, here arrow() uses this from the outer user.sayHi() method:

let user = {
firstName: "Ilya",
sayHi() {
let arrow = () => alert(this.firstName);
arrow();
}
};
user.sayHi(); // Ilya
  • Now why use This keyword?

This keyword gives flexibility. Like you just think if in that person object any instance changes to another value like if in future age changes to 53 that in that time this keyword come into picture it just set the age variable to the getbirthYear method that we need not to worry to change everything in this code.

There are many facts related to this keyword some

this Keyword is not bound

In JavaScript, keyword this behaves unlike most other programming languages. It can be used in any function, even if it’s not a method of an object.

There’s no syntax error in the following example:

function sayHi() {
alert( this.name );
}

Please note that arrow functions are special: they have no this. When this is accessed inside an arrow function, it is taken from outside.