YDKJS: LHS v/s RHS assignments in Javascript

I remember giving my first live coding interview 2 years ago. That was the first time I realised that I infact didn't know javascript as deep as I would like.

Javascript is a weird language, it has weird parts and weird behaviors. Weird not because it's a bad language, but weird because most of us don't take time to learn about them. So this october, I have decided to take on the challenge to go through famed 'you don't know javascript' series of books and write down blog posts for things that I find interesting or things that I believe can be explained differently.

Let's consider this code snippet

xvar = "inder";

Variable xvar is not defined explicitly but javascript being the helpful adorable creature that it is will create a variable for you anyway. However take a look at following code

console.log(yvar);

Here too, yvar is not defined explicitly but if you run above code, it will give a reference undefined error. Why can't it just create an empty variable and console log undefined instead? What's the difference here?

The difference is xvar had an LHS (Left Hand Side) assignment where as yvar had a RHS (Right hand assignment) assignment. Whenever the variable name is on left hand side of assignment operator = it's called LHS assignment. When the variable is on right hand side or in other words when engine is looking for value of the variable, it's called RHS assignment. In LHS assignment Javascript engine will be helpful and create a variable even if it's not defined earlier BUT in RHS assignment it would throu a reference undefined errror.