DEV Community

Mohmed Ishak
Mohmed Ishak

Posted on

1

The "This" Keyword in JavaScript Simplified (Short & Concise Article)

Hey guys. The "this" keyword in JavaScript can be very confusing because the creators of JavaScript made that keyword play multiple roles which could confuse a developer. In this article, I'll summarize the usages of the "this" keyword.

[1] "This" in a Method

A method is just a normal function but which is a part of an object. Any usage of "this" in a method refers to the object it is in. For example, take a look at this key-value pair:

const person = {
  name: "Ishak",
  birthYear: 1831,         
  age: function() {
    return 2021 - this.birthYear;
  }
}
Enter fullscreen mode Exit fullscreen mode

[2] "This" as a Standalone Keyword

If you find any "this" keyword lying around in your JavaScript file, it refers to the global object (window object in browser and global in Node).

this.isALineOfCode;
Enter fullscreen mode Exit fullscreen mode

[3] "This" in a Function

While methods are functions that is part of an object, a function is a standalone code. Since it is not attached to any object/parent, "this" in a function refers to global object (window object in browser and global in Node).

function doSomething() {
  return this;
}
Enter fullscreen mode Exit fullscreen mode

[4] "This" in Function in Strict Mode

While developers would usually prefer to use TypeScript if they want to be strict, strict mode is a great option for starters. In strict mode, if you write "this" in a function, you'll get undefined.

"use strict";

function doSomething() {
  return this;
} 
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay