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

Hi there! I'm a software professional with over 13 years of experience in developing software products. My passion lies in web development, and I specialize in using React to create engaging and user-friendly websites. Recently, I've embarked on an exciting journey into the world of machine learning, eager to explore its endless possibilities. Join me as I share my experiences, insights, and discoveries through my blog, where we can dive into the fascinating realm of software development, web development with React, and the exciting field of machine learning. Let's learn and grow together!
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 —
thisand 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?

Here’s the fiddle, go and prove it.
Don’t be in a hurry.

Photo by Duane Mendes on Unsplash
Did you really try the exercise? If not, please do so.
How was the exercise?
- Easy, I solved it in a minute. I was right, I did know
this. Great! - Difficult, I took some time but was able to solve it. Interesting.
- Could not solve it. Sorry, I still don’t know how
thisworks. 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




