DEV Community

loading...
Cover image for LHS and RHS references in Javascript? Think like a compiler!

LHS and RHS references in Javascript? Think like a compiler!

comscience profile image kapeel kokane ・2 min read

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:
Alt Text

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:

Discussion (0)

Forem Open with the Forem app