In this shot, we will discuss the function and block scopes in JavaScript. The scope is nothing but the accessibility of your variables, i.e., when and where you can access a particular type of variable.
This scope means that the variables are only accessible in the function in which they are declared.
Consider the code below:
function fun(){var temp ="temp is defined in function scope";console.log(temp);}fun();console.log(temp);
Explanation:
console.log(temp)
statement on line 8 throws an error because the temp
variable is not accessible outside the function it is declared in.The block scope of a variable means that the variable is accessible within the block that is between the curly braces.
Consider the code below:
if(true){var v1 =10;let v2=20;console.log(v1);console.log(v2);}console.log(v1);console.log(v2);
Explanation:
if
block and printed them to the console.v2
. As var
variables are function-scope based, we can access v1
; however, let
variables are block-scope based, which means that v2
will not be accessible outside the if
block.