Block scope/Local scope

Hello, I can’t seem to find anything that explains the difference between Local and block scope. Are they the same? Or does local scope only refer to the variable?

W3Schools reference scope as local and global, and codecademy only reference block and global.

has w3schools even updated to es6? They are not known for there update speed (among other problems), it used to be horrible, w3schools is better but still not really good

to truly answer this question we need to delve into Javascript. Just like many other pieces of software, programming languages get updates.

currently, Javascript is at emcascript2015 (also known as es6), before that there was es5 (and we are not going further back)

es5 had var, lets look at an example:

var one = "global";

function example(){
  var two = "local";
  console.log("inside the function: ")

example(); // call the function to execute

console.log("outside the function: ");

one has a global scope, i can access it anywhere. two has a local scope, it only exist inside the function. If you try to log two to the console outside the function (uncomment last line), you will get an error.

so var gives two options: global or local scope

in es6 (released in 2015, which could be deduced from emcascript2015 name) introduced let and const where introduced. We can create local and global variable with const and let just like var, but let and const have a block scope where as var has a function(al) scope.

function example(){
  if (true){
    let one = "block scope"
    var two = "functional scope"
    console.log("inside the if clause/block: ");
  console.log("outside the if clause/block: ");

both one and two are declared within the if block/clause. however, one only exist within if block/clause given it has a block scope. While two has a functional scope, so it can be accessed after if clause (but within the function) while one can not be accessed outside the if clause/block

same as before, run the example, then uncomment the comment, and you will you get an error.

so we have 4 things:

global scope
local scope
functional scope
block scope

I hope this helped.

1 Like

Thank you so much @stetim94

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.