I was trying to learn about javascript scope. I read a few articles and found out that let and const have block scope.
so something like this is as expected:
codeblock 1:
function letScopeTest() {
let a = 'a';
console.log('in letScopeTest scope', a);
if(true){
let a = 'b';
console.log('in if scope', a);
}
console.log('in letScopeTest scope', a);
}
letScopeTest();
Also, I read that var and function declaration get hoisted in javascript and they don’t have block scope like let
and const
.
So, I wrote this snippet which is also at some point understandable:
codeblock 2:
function checkShape() {
var shape = 'square';
console.log(`'shape' variable got declared in checkShape Scope`,shape);
var shape = 'rectangle';
console.log(`'shape' variable got reassigned value 'rectangle' in checkShape Scope`,shape);
if(true){
console.log(`'shape' function declaration got hoisted in checkShape Scope`,shape);
function shape() {};
console.log(`'shape' function declaration found in checkShape Scope`,shape);
shape = 'triangle';
console.log(`'shape' function declaration got reassignment in if Scope`,shape);
}
console.log(`'shape' function found in checkShape Scope`,shape);
}
checkShape();
But things get interesting when swap shape = 'triangle';
with function shape() {};
Something like this:
codeblock 3:
function checkShape() {
var shape = 'square';
console.log('1',shape);
var shape = 'rectangle';
console.log('2',shape);
if(true){
console.log('3',shape);
shape = 'triangle';
console.log('4',shape);
function shape() {};
console.log('5',shape);
}
console.log('6',shape);
}
checkShape()
If I remove if statement then the result is still understandable:
codeblock 4:
function checkShape() {
var shape = 'square';
console.log(`1`,shape);
var shape = 'rectangle';
console.log(`2`,shape);
// if(true){
console.log(`3`,shape);
shape = 'triangle';
console.log(`4`,shape);
function shape() {};
console.log(`5`,shape);
// }
console.log(`6`,shape);
}
checkShape();
because variable assignment gets precedence over function declaration as shown in codeblock 4.
But why codeblock 2 and codeblock 3 is not yielding the same result? I am bit new to javascript. can anyone please help me understand what exactly is happening in codeblock 2 vs codeblock 3 or point me to some resource to understand the behavior?