Scopes in Javascript

mqshaikh8

Mohammed Shaikh

Posted on January 16, 2020

Scopes in Javascript

There are 4 types of scopes in JavaScript. The global, function, block, and lexical scopes.

Variables in the global scopes can be accessed anywhere in the code. They are declared by not adding the variable declaration term (var, let, const) before the identifier.

function funcWithGlobalVariable(){
  globalVariable = “I am declared without the identifier”
}

function test2(){
  console.log(`${globalVariable} is the best`)
}
funcWithGlobalVariable()
test2()
Enter fullscreen mode Exit fullscreen mode

We are declaring the variable in function test and access in test2. However, if we declare it as:

function funcWithGlobalVariable(){
  globalVariable = “I am declared without the identifier”
}

function test2(){
  console.log(`${globalVariable} is the best`)
}
funcWithGlobalVariable()
test2()
Enter fullscreen mode Exit fullscreen mode

This would error out because the declaration and the invocation of the variable are in different scopes.

ReferenceError: bestMod is not defined
Enter fullscreen mode Exit fullscreen mode

Variables in function scope exist inside the function. All variables that are declared inside the curly brackets, stay in the curly brackets. Continuing from the example above:

function test(){
  let bestMod = "mod3"
}

function test2(){
  console.log(`${bestMod} is the best`)
}
test()
test2()
Enter fullscreen mode Exit fullscreen mode

let,const and var make the variable function scoped. The above code will give the same error as above.

Variables in block scope exists inside a block of code.

for(let i=0;i<10;i++){
   ...
}
console.log(i)//this will give an error
Enter fullscreen mode Exit fullscreen mode

The "i" does not exist outside of the for loop, so the console.log line will return an error.

Last but not least, lexical scope. Lexical scope means that in the hierarchy of code, everything under the level of where it was declared can access the variable.

function test(){
  let bestMod = "mod3"
   test2()


    function test2(){
      console.log(`${bestMod} is the best`)
    }
}


test()

Enter fullscreen mode Exit fullscreen mode

The above code will work because "bestMod" used in "test2" is declared in the function that is wrapping it. This scope was the hardest for me to remember coming from ruby where I would have to pass it in to the function for me to be able to access it.

In all of the four scopes, it is better to go from the lowest to the highest. It is always a good practice to keep the variables in block scope or function scope. Global scope, no matter how enticing it may be, is always to be avoided.

💖 💪 🙅 🚩
mqshaikh8
Mohammed Shaikh

Posted on January 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related