The Preface
Before getting into the references, do you know whether Javascript is a compiled language or an interpreted language? Well, it follows what we call a JIT (Just in Time) compilation wherein just before execution, the code is compiled into bytecode.
If you do not have an idea about this, check out this video:
The concept
Now, coming to the concept. Take this code snippet below as an example:
We can see that the variable a appears thrice. But, there is a difference in the way that the compiler looks at this code. The first 2 instances where we can see a are LHS references and the last one inside of console.log is an RHS reference. But what's different you ask?
Explanation
- An LHS reference is the one wherein the compiler tries to access the container, or to be more specific, the address that is represented by the variable.
- An RHS reference is the one where the compiler tries to find the value that is held by the variable.
They are called LHS and RHS because of the sides of the assignment operator they appear on, usually.
Now, looking at the example we can see how that makes sense. In the first line,
function foo(a) {
inside the function definition, the compiler first creates a variable a(implicitly) that is scoped to the function. Right after, an LHS reference for a happens (finding the container) and then the value, 2 is populated inside.
In the next line, again,
let a = 10;
another LHS reference has to be made and in order to get the container and the value stored in that container is changed to 10.
And in the last line,
console.log( a );
This time around, an RHS reference is required to fetch the value that is presently stored in the variable in order to log it.
And that's how all that works out. Next time around, try to think all the Javascript code that you come across in terms of references and you will actually strengthen your knowledge of how the compiler functions.
Cheers!
ps:
If you are a Javascript fanboy like me, You'll love this tweet:
Top comments (3)
Just wanted to clarify one thing, please correct me if i am wrong. Reading your article felt like LHS and RHS happening simulataneously. But what i thought was, the LHR and RHS happens in multiple passes.
So first only LHS is executed, that means only the declaration of variables takes place along with function declaration. After that RHS comes to play and assigns value to variables and executes the function.
Am i getting this wrong ?
Hey Humza. What you were talking about is the compilation and execution phase which happens one after the other. But as the code is getting executed, the LHS and RHS references get computed simultaneously.
Ah understand so basically the LHS and RHS happens inside the execution phase ?