Var, Let, Const, and Functional vs. Block Scope in modern Javascript

What Is Functional Scope vs Block Scope?

Functional scope is created by creating a named or anonymous function.

Block scope is created by an if statement or a switch statement.

Both functional scope and block scope use curly braces in javascript { }. so be careful to note if your curly braces are defining a function, an if statement, or a switch statement.

If Statements

Here’s let’s create a variable zar inside of the block scope created by the if statement.

 function App() {
   if (2+2 === 4) {
     let zar = 'a string';
   }
 

   console.log(`zar is ${zar}`)
   return (
     <>
     </>
   );
 }
 export default App;

Oops!

Can you see what I did wrong here?

The code example above doesn’t work because let creates a block scope that exist only within the if statement.

Once the if statement ends, the variable zar is then out of scope, so it can’t be accessed in the console.log statement.

Switch Statements



function App() {
  if (2+2 === 4) {

  }

  switch(2+2) {
    case 4:
      let zar = 'a string';
      break;
  }

  console.log(`zar is ${zar}`)

  return (
    <>
    </>
  );
}


export default App;