Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What is function and block scope in JavaScript?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
Function scope in JavaScript

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);
Block scope in JavaScript

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.

RELATED TAGS

javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring