Functions and its Execution Context

Today, I learned all about functions and different attributes such as: - Scopes of functions - Global and Function scopes

Global scopes: Global scopes are created on the window object. Any variable declared in the global scope can be accessed anywhere.

Function scopes: Function scopes apply to variables created inside a function. If we try to access the variable outside the function, we will get a 'Reference Error'.

Variables declared with 'const' and 'let' keywords are block scoped, meaning they are accessible only within the block whereas variables declared with 'var' keyword is function scoped.

                            
                //Declaring a global function variable called x
                let x = 10;

                //referencing 'x' in a global scope
                console.log(x, 'in global scope'); //10 'in global';
                
                //referencing 'x' inside a function
                function run(){
                    console.log(x, 'in function scope'); //10 'in function';
                }

                run();

                //referencing 'x' inside a block
                if(true){
                    console.log(x, 'in block scope'); //10 'in block'
                }

                //Declaring a variable in a function scope
                function add() {
                    const y = 50;
                    console.log(x + y, 'in function scope'); // 60 'in function scope'
                }
                add();

                //If we try to access 'y' outside the function scope, we will get a 'Uncaught Reference Error'
                console.log(y); //Uncaught ReferenceError: y is not defined

                ------------------------------------------------------------

                // An If statement is a block
                if(true) {
                    console.log(y); //10
                    const a = 100
                    console.log(a + y) //110;
                }

                //If we try to access 'a' outside the block scope, we will get an ReferenceError
                console.log(a); //Uncaught Reference Error

                //A loop is a block
                for(let i = 0; i < = 10; i++){
                    console.log(i); //1, 2, 3, 4, 5, 6, 7, 8, 9, 10
                }

                //Difference between 'var', 'let' and 'const'
                //var is function scoped, meaning it can be referenced from anywhere

                if(true){
                    const a = 100;
                    let b = 200;
                    var c = 300;
                }

                console.log(a); //Uncaught ReferenceError;
                console.log(b); //Uncaught ReferenceError;
                console.log(c); //300 'because var is accessible outside a block scope'
            
        

File Info

Category HTML / JS / CSS
Credits NA
Date February 10th, 2025
Codepen NA