@Davenewton 's answer is correct and while I like it for its
straightforwardness, it takes that
famous a-ha! moment for you to fully
realize why. Here's what's really going on:
So to elaborate
If we had something like this:
function i_am(){
var a = 'very smart person';
console.log(this.a);
}
var a = 'monkey';
i_am();
Depending on what linter or browser you might be using, this might either return
> "monkey" // (try the snippet)
or also
> "monkey"
> undefined // check the sreenshot

This is because of one simple reason, best understood if we go step-by-step how compiler "reads" the code.
- hoist the
function i_am() declaration to top (undefined)
- hoist the
var a declaration to top (undefined)
- assign
'monkey' to variable a (now string "monkey")
- execute/invoke the
i_am() a function we have pre-declared
- create a local variable
a and assign string "very smart person"
console.log(this.a) returns 'monkey', because this refers to var/property a (same thing in this case) of the global object - call-site is from global object : i_am();
- Finish execution - but uh oh! We executed function and returned no value!
Now, depending on your environment, either it hides the undefined result from you, or it prints it out! Why? Because functions are looking to return a value. Just like with variable declaration, if you do
it has not been assigned a value, hence it results after RHS in undefined.
Similar principle applies to function, where it's looking to return a value, but it doesn't return anything, hence resulting in undefined
In other words, it's not this that returns undefined. It's the invokation of i_am(); that returns undefined!
Hopefully it's clear to everybody now :)