Need a little explanation on the behaviour of this codes

1st CODE :

let i = "outside block"
if(true){
    let i = "inside block";
}
console.log(i);

1st CODE O/P :
outside block

2nd CODE :

let i = "outside block"
if(true){
    var i = "inside block";
}
console.log(i);

2nd CODE O/P :
var i = “inside block”;
^
SyntaxError: Identifier ‘i’ has already been declared

You can only declare a variable once within the same scope using let. But you aren’t declaring the second i in the same scope, it has its own block scope you say. Actually, var doesn’t abide by block scope, so the second i is actually in the same scope as the first i and thus you can’t do that because you used let for the first i.

Set those both to var and you won’t get the syntax error.

2 Likes

It’s been so long since I’ve used var to declare a variable that I didn’t realize it worked that way. I know it doesn’t abide by block scope, but I had no idea that it would attempt to redeclare variables of the same name in the top level scope by default.

FCC has an article on variable hoisting which is what is going on here. Any variable declared with var will always be either at the top of the functional scope or in the global scope.

There is a difference. The first i was declared with let, which is why a syntax error is being thrown when using var for the second i. If the first i was declared with var there would be no syntax error.

The moral of the story here is to always use either let or const to declare variables. There are very few use cases that would justify the necessity of using var (some would argue there are none) and you better understand the differences if you do feel the need to use var :smiley:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.