Scope and hoisting By Chloe
Global Scope
A variable declared outside of another function is in the global scope.Local Scope
A variable defined inside of a block/function is in the local scope.Variable and Scope
Variables with the VAR keyword are always 'function-scoped' - meaning they recognize functions as having a seperate scope. In the following example the locally scoped variable is not accessible by the global scope.var name = "Chloe"; function greet() { var name = "George"; console.log(`Hello my name is ${this.name}`); } console.log(name); => Chloe greet(); => George.Variables defined using the LET and CONST keywords are 'block-scoped' - meaning a new local scope is created from any kind of block (as apposed to only functions), i.e. functions, if statements, for and while loops.
var drink = true; let age = 17; //initialize global variable. if(drink) { let age = 21; //local variable initialized. console.log(`You are ${this.age} enjoy a G and T`); } console.log(`You are ${this.age} enjoy a pepsi`) =>You are 21 enjoy a G and T =>You are 17 enjoy a pepsi
Hoisting
Hoisting is JavaScripts default behaviour of moving all declarations to the top of the current scope. I.e to the top of the current script or current function.