Understanding this keyword in Javascript
In this article, We will learn about the keyword 'this' in Javascript.

this keyword in javascript is one of the most important concept every javascript developer need to understand.
What is this keyword? 🤔
thiskeyword is special variable which is created for every execution context. It is used to access the properties and methods of the object which is currently executing. Value ofthisvariable depends on many factors that we will discuss in this article.
Important points about this keyword 🧐
👉 this variable is created for every execution context.
👉 this is not static. It's value depends on how the function is called.
1. If function is method of an object
In this case this variable refers to the object.
Example:
const person = {
  name: 'Rakesh',
  age: 25,
  sayMyName: function () {
    console.log(`Hello ${this.name}`)
  },
}
person.sayMyName() // Hello RakeshIn above example, this variable reffering to person object.
2. If function is a regular function
If we run javascript in strict mode, then value of this variable will be undefined otherwise it will refers window object.
// In strict mode
'use strict'
function printThis() {
  console.log(this)
}
printThis() // undefined
 
// In non-strict mode
function printThis() {
  console.log(this)
}
printThis() // window
In above example, value of this variable is undefined in strict mode and window object in non-strict mode.
3. If function is a arrow function
Arrow function doesn't have it own this variable. It's value is same as that of the function where it is called.
// In strict mode
'use strict'
const printThis = () => {
  console.log(this)
}
printThis() // window
 
// In non-strict mode
const printThis = () => {
  console.log(this)
}
printThis() // windowIn above example, value of this variable reffering to the window object in both strict mode and non-strict mode.
As printThis function is a arrow function and it will not have it's own this variable.
4. If function is event handler
In this case this variable refers to the DOM element on which the event is attached to.
const button = document.querySelector('button')
button.addEventListener('click', function () {
  console.log(this)
})
// <button>In above example, value of this variable reffering to the button DOM element.
More Articles
Top 10 Best JavaScript Clean Syntax Alternatives to Complex Syntaxes
In this article, we explore the top 10 best JavaScript clean syntax alternatives to simplify your code and make it more readable and maintainable.
June 28, 2024
Implement lodash's `.get` method
In this article, We will try to implement basic funtionality of lodash's `.get` method
December 5, 2022