JavaScript Interview Coding Problem - let keyword

This video covers a programming problem on JavaScript let keyword and its scope.

Code

let a = 10;
{
let b = 20;
{
let a = 90;
console.log(a + b);
}
console.log(a + b);
}

Full Transcript

Here's the JavaScript quiz question for today. We need to find the output of this code, but we should also understand the reason why we get a specific output. So let's start. First thing, you may have noticed that all the variables are declared and initialized using let keyword. Now let keyword allows you to declare an optionally initialized variables that are confined to the scope of a block, which means our variable a can be accessed anywhere in this file. Variable b can only be accessed within this scope. And the second variable a is only accessible within the scope. No one can use it outside of the defined scope. So when we logged the value of a + b right here, it takes the value from this variable a, which is 90. Since it found the variable it was looking for, it will not look anywhere else. Variable b is already accessible anywhere between this block scope, so it's value 20 is added to number 90, which gives us 110. Now the next console.log statement again adds a and b and log its value. This time when it tries to access variable a it gets the value from here, which is 10. You must be thinking why it did not access variable a is equal to 90? That's because variable a=90 is only accessible within this block scope and anyone outside of the scope, cannot access it. However, that's not the case with variable a=10, which can be accessed anywhere in this entire scope. So the second log statement adds value a=10 and b=20, which is already in its scope and gives us the result 30. And this is our actual output.