javascript change global let value code example

Example 1: javascript var let

// var has function scope.
// let has block scope.

function func(){
  if(true){
    var A = 1;
    let B = 2;
  }
  A++; // 2 --> ok, inside function scope
  B++; // B is not defined --> not ok, outside of block scope
  return A + B; // NaN --> B is not defined
}

Example 2: change a variable outside a function js

var global = "Global Variable"; //Define global variable outside of function

function setGlobal(){
       global = "Hello World!";
};
setGlobal();
console.log(global); //This will print out "Hello World"

Tags:

Misc Example