Hi @gaurav_t!
You figured it out. Your logic on your second post is correct.
Considering the second post (with apple
and mango
), let’s check the results.
Using let
:
Block scope i is: mango
Function scope i is: apple
apple
Using var
:
Block scope i is: mango
Function scope i is: mango
mango
That’s happening because with var
the code var i = "mango"
inside the if
statement is overriding the code var i = "apple"
.
Since var
is a function scope declaration, if you declare it again, even inside another block, but in the same function, you’ll be given the variable another value.
With let
this won’t happen, since let
is block scope. So, for every block of code, you can declare a variable with the same name and they will have their value only inside that block (unless you are returning the value for another function or something).
Just be sure to avoid doing this, name each variable with something meaningful to make it easier for you and others to read your code. Usually, you will only see variables using the same name in loops. Names like (i for index).
Line by line:
function checkScope() {
/*-----------------------function scope------------------------*/
"use strict";
let i = "apple"; /* i is declared and given the value of a string "apple". */
/*-----------------------block scope------------------------*/
if (true) {
let i = "mango"; /* i is declared again, but since "let" is block scope, this is not the same i as above.
It is a new "i variable" that will only have the string value of "mango" inside this block. */
console.log("Block scope i is: ", i); /* log will be called and the value of i here is "mango". */
}
/*-----------------------block scope------------------------*/
console.log("Function scope i is: ", i); /* log will be called and the value of i here is "apple".
That's because it's value was not replaced by the value of the variable i declared
inside the "if block". */
return i; /* as the log just above, i in here is the same i declared in the start of
this function, the value has not changed. */
}
/*-----------------------function scope------------------------*/
let test = checkScope();
console.log(test)
I hope it’s good for you to have an idea of the difference, but I’m sure you already understood it, considering what you said in your second post.