Understanding JavaScript Variable Scope

Understanding JavaScript Variable Scope

If you are reading this article, you are reading my first article. As a newbie in JavaScript, the fundamental word I heard a lot was variables. It was mentioned in every book, article, and tutorial on JavaScript I came across. That's because, in every JavaScript file, a variable must be used.

In this article, we will learn the JavaScript variable scope, and also the concept of the keywords used in variable declaration. Please always try out the examples in your dev tool it will help you understand better.

What is a variable?

A variable is a named 'container' for storing data. We use variables to store and manipulate different data types. Whenever we declare a variable we use these keywords: var let const. Variable scope determines the accessibility of that variable in JavaScript code. Variables can be declared at different scopes viz

  • Global Scope
  • Local Scope

Global Scope

Variables with global scope can be accessed anywhere within the same JavaScript file. Any variable declared outside a block of code in a JavaScript file has a global scope. A block in JavaScript is any line(s) of code enclosed between two curly brackets ({}). The block of code could be a function block, a loop block, a conditional block, etc.

let myName = 'Orbie';
function letGlobalScope() {
  console.log(myName) // Orbie
  let color = 'Green';
  if (true) { 
    let height = 1.8
    console.log(color)
    // Green, color is accessible in the if block because it is globally scoped relative to the function block.
    // it can be accessed anywhere in the letGlobalScope function
  }
  console.log(height) // 30, height is not accessible.
}
letGlobalScope()
console.log(color) // color is not accessible outside the function block.

In the code above, the variable myName can be accessed anywhere within the file because it has a global scope. While the variable color can be accessed anywhere within that function block because it has a global scope relative to the function block. But outside the function block, color is not accessible. it will be discussed in the section that follows.

Local Scope

Variables declared within a block of code in a JavaScript file are said to have a local scope because those variables can only be accessed within that block of code. Since local variables are only recognized within the block they are declared, the same variable names can be used within different code blocks.

Local variables are created when the block of code within which they are declared is executed and deleted when the execution of that block is completed.

function letLocalScope() {
  let myAge = 30; 
  if (true) {    
    // variables declared inside the if will not be accessed outside the if block
    let color = 'Blue';
    let sum = 20;

    console.log(color) // Blue
    console.log(sum) // 20
    console.log(myAge) // 30
  }  
  console.log(color) //Uncaught ReferenceError: color is not defined color is not accessible because color has a local scope. It's only accessible in the if block
  console.log(myAge) // myAge is accessible because it has a local scope. i.e it's only accessible in letLocalScope function block.
}
letLocalScope()
console.log(myAge) //Uncaught ReferenceError: myAge is not defined

In the code above, the variable myAge can be accessed anywhere within the function letLocalScope because it has a local scope. However, it cannot be accessed outside that function block.

The Scope of the var let and const Keywords
Before 2015, variables can only be declared with the var keyword, in 2015 ECMAScript introduced let and const important JavaScript keywords.

The var Keyword

Variables declared with the var keyword are declared globally, or locally if declared inside a function, and these variables cannot have block scope. Whenever variables are declared with the var keyword you can redeclare that variable without an error. However, using the var can impose problems in your code. So be mindful of how you declare with var.

var color = 'blue'; 

if(true) {
   var color = 'pink';
   console.log(color) // it logs pink
}
console.log(color) //It logs pink instead of blue

The let Keyword

When a variable is declared with let, it's scoped to all block codes(function block, if block, loop, etc).

let name = 'Orbie'; 

if(true) {
   let name = 'Moween';
   console.log(name) //Moween 
}
console.log(name) //Orbie

The const Keyword

A variable declared with const, it's scoped to all block codes(function block, if block, loop, etc). Once a variable is declared with the const keyword, it cannot be reassigned

const gravity = 9.81;
gravity = 1.5;
console.log(gravity) //TypeError: Assignment to constant variable.

Conclusion

Javascript variables are a fundamental part of programming. So, understanding JavaScript variables scope during declaration will help you a lot. It's kinda problematic to declare variables with the var keyword, so avoid using it. As a Javascript developer, it is best practice to declare variables that will be reassigned with the let keyword, and the variables that will not be reassigned in your code with the const keyword.

Resources

FreeCodeCamp JavaScript Info W3Schools Javascript

Thank you for reading this article. Please feel free to like, comment and share.