2

I was reading the Scopes and Closure title of You don't know JS by Kyle Simpson, specifically this topic Compiler Speak. This section is about the kind of Lookups the engine uses. Now I understand what is LHS or RHS lookup to the extent given in this section.

My problem is the note saying that function declaration of the form function fx(a) {.. is not a LHS lookup. There is an explanation given for the same, but I am unable the understand. Here is the whole note

You might be tempted to conceptualize the function declaration function foo(a) {... as a normal variable declaration and assignment, such as var foo and foo = function(a){... . In so doing, it would be tempting to think of this function declaration as involving an LHS look-up. However, the subtle but important difference is that Compiler handles both the declaration and the value definition during code-generation, such that when Engine is executing code, there’s no processing necessary to “assign” a function value to foo . Thus, it’s not really appropriate to think of a function declaration as an LHS look-up assignment in the way we’re discussing them here.

Any kind of clarification would be helpful. Even on LHS and RHS lookups.

Akshendra Pratap
  • 2,002
  • 1
  • 12
  • 25

2 Answers2

2

The topic of "lookup" is one that has to do with expression evaluation. A function declaration statement

function someName() {
  // code
}

is not an expression. It's a distinct statement type in the same way that return is a distinct statement type, and while and if. No expression evaluation happens in a function declaration statement, other than the implicit instantiation of a new function object to be bound to the function name in the local scope.

The topic of LHS and RHS values (usually, in my experience, called l-values and r-values in the literature) is important, but it just has nothing to do with function declarations.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

I shared the same question while reading. Pointy's answer above made the concept pretty clear, and I am just adding more explanation using the quote from a newer edition of the book:

"function getStudentName(studentID) {

A function declaration is a special case of a target reference. You can think of it sort of like var getStudentName = function(studentID), but that's not exactly accurate. An identifier getStudentName is declared (at compile time), but the = function(studentID) part is also handled at compilation; the association between getStudentName and the function is automatically set up at the beginning of the scope rather than waiting for an = assignment statement to be executed.

NOTE: This automatic association of function and variable is referred to as "function hoisting", and is covered in detail in Chapter 5."

Here is the link to the new edition on GithHub.

Jun Yin
  • 2,019
  • 3
  • 16
  • 18