What Is Scope Concept In JavaScript?
The scope is a very important concept in every programming language. But it works differently from language to language. Here I’ll explain JavaScript scope in detail.
Definition:
Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript.
1)Function:
Consider we created a function named ‘scopeconcept’. And then declare a variable x=2, And finally console log, then it will print 2 in our console.
But if we console log outside the function, then it will not print 2 in the console. In such cases, the scope concept comes into play. Scope of variable x is limited inside the function ‘scopeconcept’.
Conclusion : If we declare
var x= 2,
let y= 3 ,
const z= =4 ;
inside the function then these are local i.e. can be accessed only inside the function
2)Loop
If we created a variable inside ‘if statement’, for loop, while loop, then you can access the variable globally.
Conclusion : If we declare
var x= 2, // globally
let y= 3 , //locally
const z= =4 ; //locally
inside the ‘if statement’, for loop, while loop, then you can access variable globally while element declare with let and const can be accessed locally.
More resources :
https://freeguideex.blogspot.com/2021/02/what-is-scope-concept-in-javascript.html