What is function and block scope in JavaScript?

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.

Function scope

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:

  • When we run the above code, we can see that the console.log(temp) statement on line 8 throws an error because the temp variable is not accessible outside the function it is declared in.

Block scope

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:

  • From lines 3 to 6, we defined some variables in the if block and printed them to the console.
  • When you run the above code, you can see that an error occurs while printing the variable 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.