JavaScript, starting with ES6, offers 3 types of scope:
- global scope - using var - (not recommanded; for backward compatibility)
- block scope - using let or const - (recommanded approch)
- function scope - variables declared inside a function
OBS:
1. const doesn't allow you to change the value of a variable after declaring it. Just like a constant.
2. It doesn't matter if you use var, let, or const to declare variables inside a function. They aren't visible outside that function, unless returned. Module Design Pattern is based on this approch.
// global scope example
const PI = 3.1415;
if(PI == 3.1415) {
var euler = 2.72
euler++
}
console.log(euler); // output: 3.72
// functional scope example
function say_boo(){
var boo = "Boo"
console.log(boo);
}
say_boo(); // output: "Boo"
console.log(boo); // output: "error"
// block scope example
const PI = 3.1415;
if(PI == 3.1415) {
let euler = 2.72
euler++
}
console.log(euler); // output: "error"
JavaScript, starting with ES6, offers 3 types of scope:
- global scope - using var - (not recommanded; for backward compatibility)
- block scope - using let or const - (recommanded approch)
- function scope - variables declared inside a function
OBS:
1. const doesn't allow you to change the value of a variable after declaring it. Just like a constant.
2. It doesn't matter if you use var, let, or const to declare variables inside a function. They aren't visible outside that function, unless returned.
Module Design Pattern is based on this approch.