While learning javascript, I came across 2 different code snippets and I am confused about the scoping of variables declared using let/const. I know that variables declared using let/ const are block-scoped, meaning you can’t access them outside the block in which they are declared.
The following two snippets contradict each other, why is that so?
Snippet 1: ReferenceError as expected
const calculateArea = function(radius){
let area = 3.14 * radius ** 2;
console.log(area);
}
console.log(area)
Output of snippet 1:
ReferenceError: area is not defined
at <anonymous>:12:13
at mn (<anonymous>:16:5455)
Snippet 2: Why no error???
let age = 30;
if(true){
let age = 40;
let name = 'Peter';
console.log('Inside if block: ', name, age);
}
console.log('Outside if block: ', name, age);
Output of snippet 2:
Inside if block:
Peter
40
Outside if block:
30
Why is there space before age while logging outside if block statement to console?
Why was there no reference error this time?