Niranjan Borawake
W3H - What Why When How

W3H - What Why When How

Do You Really Know JavaScript’s ‘this’ Keyword?

Do You Really Know JavaScript’s ‘this’ Keyword?

Niranjan Borawake

Published on Jun 25, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

How many times in your professional career have you felt that you knew something, but when you needed to explain it to someone or came across an interesting blog post about it, you calmly reminded yourself, "No, I didn't know it."

If you're a JavaScript developer, there's a good chance this has happened to you with the this keyword.

Because as they say —

There are only 2 things that are hard in JavaScript — this and everything else.

If you are new to JavaScript and landed here to understand how the this keyword works, then this is not the right place. Please head to the MDN docs here.

Okay. You're still reading this. So you believe you are an experienced JavaScript developer who understands this.

Would you mind going through a very quick exercise to prove it?

Prove you understand this

Here’s the fiddle, go and prove it.

Don’t be in a hurry.

Some things take time

Photo by Duane Mendes on Unsplash

Did you really try the exercise? If not, please do so.

How was the exercise?

  1. Easy, I solved it in a minute. I was right, I did know this. Great!
  2. Difficult, I took some time but was able to solve it. Interesting.
  3. Could not solve it. Sorry, I still don’t know how this works. So, you were wrong.

Please note that we kept the exercise simple to focus only on this and did not consider arguments passed in the printMessage function.

If you fall under the #1 category, then you might want to try passing a few values to printMessage , use them, and then try to make it work again.

Albeit, here is a very simple solution to the exercise.

I hope it was worth the exercise. For a full-proof solution, have a look at bind polyfill here.

As per Kent C. Dodds’s recent tweet —

If this is a problem for you, could it be possible to eliminate the complexity of this ?

In my opinion, yes. Switch to functional programming. Here’s my take on the very basic concepts of functional programming.

Photo by sydney Rae on Unsplash

Did you find this article valuable?

Support Niranjan Borawake by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this