What will this function return?
(function() {
 let f = this ? class g { } : class h { };
 return [ typeof f, typeof h ];
 })();

Understanding JavaScript Function Scopes and Typeofs

The correct answer to the aforementioned code snippet is ["function", "undefined"]. This outcome is a result of how JavaScript handles function scopes and variable classifications.

Let's break this down a bit further to understand why this is the case.

(function() {
 let f = this ? class g { } : class h { };
 return [ typeof f, typeof h ];
})();

In this anonymous function, the variable f is defined and assigned a class g or h based on whether this is truthy or falsey. The "this" keyword in JavaScript refers to the object it belongs to. In the global execution context, "this" refers to the global object (in web browsers, it is the window object). If the code runs in strict mode, this will be undefined.

Consequently, if this is truthy, it will choose the class g, otherwise, it will pick class h.

The return statement is trying to return an array with the types of f and h. The typeof operator in JavaScript returns a string indicating the type of the unevaluated operand.

The typeof operator returns:

  • "function" for a function or class (since classes are functions in JavaScript)
  • "undefined" for an undeclared variable or a variable whose value is undefined.

Since f is assigned either class g or class h and is there by declared and initialized within the scope of the function, typeof f returns 'function'.

However, h is declared, but it's not necessarily initialized, hence it is not accessible within the function scope. This is why typeof h returns 'undefined'. Interestingly, if h were initialized outside the anonymous function, typeof h would return 'function'.

Thus, the crowned output would be ["function", "undefined"].

Applying These Concepts

Understanding function scopes and variable types in JavaScript is critical for good coding practices. It helps you avoid common programming bugs related to variable hoisting, and incorrect reference of the 'this' keyword. Always make sure to define and initialize your variables in the correct scope to avoid unforeseen behaviors in your programs.

Moreover, remember to be cautious with the use of this keyword not to reference an unintended scope. If you're unsure of what object this is referring to, always console log it to find out.

Do you find this helpful?