www.tektutorialshub.com/javascript/javascript-let-vs-var-vs-const/
1 Users
0 Comments
46 Highlights
0 Notes
Tags
Top Highlights
The scope or visibility of the variable is the major difference between these keywords.
The scope is a region of the program where a variable is visible. Every variable we define will become part of a scope. We can access that variable only within its scope.
JavaScript creates four Scopes. They are Global Scope, Function Scope, Block Scope & Module Scope.
The variables we declare using var inside a function are only available within that function. If we declare them outside the function, then they are available everywhere i.e. they are a global variable.
Even if we declare a var variable inside a code block, they are still scoped to the enclosing function. If there is no enclosing function, then they will become a global variable
var localVar=1000
ts scope ends where curly braces ends
console.log(localVar) //ok
onsole.log(localVar) //ok
console.log(localVar) //error
The variables declared using let or const are block-scoped. They are scoped to the block in which we declare them. A code block is anything inside curly parentheses. For Example, if condition, try/catch/ block, while loop, for loop, function, etc.
This means that we can only use it in the code block where we declare them. Outside the code block, they are invisible
If they are outside the code block, but within the function body then they become function scoped.
they are outside the function and code block, then they are available globally or become a global variable.
//defined locally //Its scope ends where curly braces ends
let localVar=100
console.log(localVar)
error
unction nested() { console.log(localVar) //error }
We can redeclare or redefine a var variable
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.