'this' Keyword in JavaScript
https://unsplash.com/photos/82TpEld0_e4?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink

'this' Keyword in JavaScript

Article content
guess the output!

In the provided code, we have two objects, someObject and someAnotherObject, both containing a getFullName method. However, one uses a regular function, and the other uses an arrow function. The key difference between these two functions is how they handle the 'this' keyword.

Here's an explanation of the output:

  1. console.log(this); In strict mode ("use strict"), when you log 'this' in the global context (outside of any function or object), it will be undefined. Strict mode prevents unintentional global variable creation, so this in the global context is not bound to any object.
  2. console.log(someObject.getFullName()); In this case, someObject.getFullName() is a regular function within the someObject object. When this method is called, 'this' inside the function refers to the someObject itself. Therefore, this.firstName and this.lastName correctly access the properties within the someObject, resulting in the output: "Shivam Pawar."
  3. console.log(someAnotherObject.getFullName()); Here, someAnotherObject.getFullName() is defined as an arrow function (() => {}) within the someAnotherObject object. Arrow functions do not have their own 'this' context; instead, they inherit the 'this' value from their surrounding lexical (enclosing) scope. In this case, the surrounding lexical scope is the global context (the window object in a browser environment).Since 'this' in the global context is undefined (due to strict mode), attempting to access this.firstName and this.lastName inside the arrow function will resulting in the output: "undefined undefined".

The output of the code will be something like:

Article content
with strict mode

If you remove the "use strict"; directive from the code, the behavior of the 'this' keyword will change, especially when used in the global context.

Without strict mode, in the global context, 'this' refers to the global object, which, in a browser environment, is the window object. So, you will see the window object logged to the console.

Without strict mode, the output of the code will be something like:

Article content
without strict mode

Conclusion:

Understanding how 'this' behaves in different contexts, whether in strict mode or not, is crucial for writing predictable and error-free JavaScript code. Developers should be aware of these nuances to effectively use the 'this' keyword in their programs.

To view or add a comment, sign in

More articles by Shivam Pawar

Others also viewed

Explore content categories