Scope and hoisting By Chloe

Scope refers tp the current context in code, which determines the acessibility of variables to JavaScript.
There are two different type of scope:

Global Scope

A variable declared outside of another function is in the global scope.
Variables in the global scope are accessible throughout the entire script.
It is best practice to avoid defining variables in the global scope (where possible), as they can be accessed by other developers - even when it is not wanted.

Local Scope

A variable defined inside of a block/function is in the local scope.
Local variables have limited visibility, when variables are defined in a function, they are local to that function and can't be accessed from outside of the function.
They only exist while the function is invoked.

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.
It is advised to define variable using the block-scoped keywords, as it reduces the risk of accidentally over-riding variables.

        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.
Variables declared with LET and CONST are not hoisted.
To avoid hoisting declare all variables are the top of every scope.