<script>
let GLOBAL_DATA = {value : 1};
</script>
Pretend in the console, that we type:
console.log(GLOBAL_DATA);
let x = 1; // global
{
let x = 2; //local
}
console.log(x); //1
var x = 1; // global
{
var x = 2; // global
}
console.log(x); //2
function outerFn() {
let x = 1;
function log() {
console.log(x);
};
function run(fn) {
let x = 100;
fn();
}
run(log);
};
outerFn(); //1
let x0 = 0;
function fn1() {
let x1 = 1;
fn2();
function fn2() {
let x2 = 2;
fn3();
function fn3() {
let x3 = 3;
console.log(x0 + " " + x1 + " " + x2 + " " + x3);
};
};
};
fn1();//0 1 2 3
1- The scope is global it can be accessed everywhere.
2- the Variable declared with Let is only accessed inside the block that is declared in so it can't be accessed outside that block, the Variable declared with Var can be also accessed outside the block that was declared in, the variables starting with var are not predictable so better not to use them at all.
3- the X in the outerfn is local for the function itself but it's considered global for its nested functions, and The X of the Run function is local for the Run function alone and it can't be accessed outside of it.
4- It's called the scope chain
5- A- The global: which can be accessed everywhere in your script, B- The Function Scope: can only be accessed inside the function box and the blocks that are in it. C- The Block scope: can only be accessed inside the curly brackets of the block.
6- Let: you can't redeclare it twice, hoisting does not occur, is block scoped BUTTTT var: you can declare it more than twice, hoisting occurs, is function scoped.
7- Strict will give us an error if there is any mistype or if we miss adding brackets or semicolons. but sloppy the javascript will assume what you meant and this may lead to weird bugs in the final project