What is THIS?!

Today at the Iron Yard we dove into a loved (and equally hated) word. That word is THIS. Yes, this. A simple four letter word that we use often to describe something we point at or have in our hand. Today I learned how it can be implemented in Javascript, and even make my coding life easier!

To break out down as simple as possible, this is a handy shortcut. It allows us to type the word this in place of the full variable name, when accessing parameters of an object. For example:

var MyName = {

firstName: Jacob, 

lastName: Burkhart


Can be called upon like so:

console.log(this.firstName + ” + this.lastName);

In this example, this is taking place of the MyName variable. It’s the same as typing out MyName.firstName, etc.

However, while this is a fun tool to use, to make coding quicker and more efficient, it has it’s nuances. This is where scoping comes into play. It is important to make sure that the use of this is inside a function where this is defined. Using this at the top of your code, then again at the bottom, does not necessarily mean the the same thing. It is only used within the function that has defined it.

I know it is a confusing subject, and to be honest I haven’t completely grasped it. This feels like a facet of Javascript that may take a few mistakes to learn from. But, from now on I will be looking for opportunities to use THIS in my code!