Understanding “Function Vs Block scoped” using ( var, let ) keywords - JavaScript
Hello Reader, I'll try my best to make you understand Function vs Block scope, assuming you have basic knowledge of JavaScript. Feel free to copy the code and try it yourself, I used Replit for all the examples.
Function Scope -
Function scope means a variable or a function declared inside another main function is available only during the execution of that main function. Scope of a function something looks like below
function main(){
var scope = “function”
function funcInsideMain(){
}
}
Let’s now understand the above with a simple example:
First thing we will create a function,
function displayName(){
var name = "muralidhar";
console.log(name)
}
displayName();
The result is as expected:
Now let's move the statement out of the function and see what's gonna happen
function displayName(){
var name = "muralidhar";
}
displayName();
console.log(name)
Result:
We get a ReferenceError: name is not defined, means the mighty Console
is telling us it doesn’t know name
and never seen it before. So from this we can understand when console.log(name)
declared inside i.e during the function displayName()
execution the variable name
is available and it’s not available when declared outside the function scope.
Block Scope -
Block scope means a variable or anything declared inside a block is not available outside a block. A block scope is something defined like below anything inside the curly braces is block scoped,
{
}
If - else
statements, for
while
do - while
loops are considered block scoped. Now let’s check that in action.
for (let i = 0; i < 5; i++){
}
console.log(i)
Result:
Now the mighty
Console
is telling us it doesn’t know i
, hence the variable i
is block scoped.
Let’s try the same example withvar
keyword:
for (var i = 0; i < 5; i++){
}
console.log(i)
Result:
Wait! What? How? ….. Is the block scope broken and stopped working? No.
It’s not the
for loop
it’s the keyword var
makes it work like that.
Learning:
var
keyword is not block scoped
, only function scoped
Kudos to you 🎉 for making it to the end of this blog. Hope you understand the basic difference between function and block scope. If you find this helpful please leave a comment, like this blog and share it.