<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
Room 7 Nina Yousif Rozhiar Maria Shahla
1- global scope because it's inside a function or inside a block
2- the first x is block statement scope because it's initialized with keyword let and the second x is global because it's initialized with var
3-In the following code, x is a global variable for all inner functions, and any changes to x after the log shall not override it since it is declared before the let x = 100 line.
4- Hoisting
5-Global variables are useful for values that are relatively constant, or that many functions in the script must access, such as a session id. A local variable, however, has a limited scope: it exists only within the block that it is declared in.
6-let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.
7-in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.------ let x;
let x =27;