All Articles

JavaScript Tricky Situations - 01

inner peace

Recently, I saw a tweet with below code lines and it asks what is the outcome of it.

let fruit = “apple”

function printFruit() {
  console.log(fruit);
  let fruit = “Banana”
}

printFruit();

Take a few seconds and think about this. What will be the outcome?

                        ...

In the above code block, we need to consider 2 main things.

  1. Variable declaration type (var, let, const)
  2. Hoisting
  3. Shadowing

I will not be going to explain those in more details manner. There is an excellent guild to explain all of these in details manner.

It is called You Don’t Know JS Yet and you should definitely check that out.

So let me explain this example. The fruit variable defines inside(Let’s call it B) the function and outside the function(Let’s call it A) are treated as 2 different variables. Because A lives in the global scope and B lives in functional scope and they are shadowing. That means it is totally legit to have 2 variables with the same name. But you need to know which one call from where.

So now we know that withing this code, there are 2 different variables in the same name. Now comes to the next point. If we define a variable from let variable definition. It will not be hoisted. That means before execution, those variables will not be initialized as ‘undefined’. But the tricky thing is JS Engine parse that code correctly. It knows there will be variable with that name. But you can’t access it from that point. You need to initialize it before use. This is called as Temporal Dead Zone (TDZ).

Because it can’t access it, it gives this error.

ReferenceError: Cannot access ‘fruit’ before initialization

This is kinda very long story in very short form. If you have anything to ask regarding this please leave a comment there. Also, I wrote this according to my understanding. So if any point is wrong, don’t hesitate to correct me. I really appreciate you.

That’s for today friends. See you soon. Thank you

Main image credit