Scope in JavaScript is divided into the Block Scope, Function Scope and the Global Scope.
Starting with the Global Scope
// Global scope
var a = 1;
let b = 2
const c = 3
console.log(`Global Scope ${a} ${b} ${c}`)
- This is a global scope and everything is fine, if you console.log the value
Function Scope
// Global scope
var a = 1
let b = 2
const c = 3
//Function scope
function num() {
var a = 10
let b = 22
const c = 5
console.log(`Function Scope ${a} ${b} ${c}`)
}
num()
console.log(`Global Scope ${a} ${b} ${c}`)
So inside the function scope we get our 10, 22, 5 while in the global scope we still get our 1, 2, 3, because they are different variables in different scope.
-
Varis a Function scope It means they are only available inside the function they’re created in, or if not created inside a function, they are ‘globally scoped..
var a = 1;
let b = 2
const c = 3
for(var a = 0; a < 10; a++) {
console.log(a)
}
console.log(`Global Scope ${a} ${b} ${c}`)
- The value of
var a = 10in the global scope. - The
var ain the loop actually changes the valuevar ain the global scope which is not good, that's the reasonletandconstwas created.
NOTE: var is kind of wired, that's one of the thing that lot of people didn't like about JavaScript. it causes security risks and it can cause confusion if you have some variables in the global scope.
Block Scope
// Global scope
var a = 1
let b = 2
const c = 3
// Block Scope
if(true) {
var a = 6
let b = 7
const c = 10
console.log(`Block Scope ${a} ${b} ${c}`)
}
console.log(`Global Scope ${a} ${b} ${c}`)
What do you think the global scope var a result will be?
The result will be
var a = 6because after declaring thevar a = 1on the global scope it was change in the block scope.Notice the
let and constdidn't change, in the global scope they retain their values and also in the block scope.
Benefit of let & const
- They aren't scoped to the function, they are scoped to the block.
- What is the block? A block is a set of opening and closing curly brackets.
Points to Take
-
varis function scope. -
letandconstare block scope. - Function scope is within the function.
- Block scope is within curly brackets.
Top comments (0)