Variable Scopes in JavaScript

Variable Scopes in JavaScript

Four types of variable scopes in JavaScript.

Β·

6 min read

Hello! everyone πŸ‘‹πŸΎ,

Welcome. In today’s post we will be learning about scopes in JavaScript with regards to variables.

Introduction

Scope in programming refers to the accessibility of a variable or a function in a program. It also refers to the parts of your code where the variable or function can be used. In this post we will be focusing on the various types of variable scope and how to create variables with a specific scope.

Types Of Variable Scopes In JavaScript

A variable’s scope refers to the parts of your code where the variable can be accessed or used. The accessibility of a variable depends on where where it is declared in the code. Depending on where a variable is declared, it can have one of the following types of scope:

Block Scope

A variable with a block scope is one that can only be accessed or used within a block of code. A block of code is a set of statements bounded by curly brackets {} in the code. For example if statements and loops (for and while loops).
To create a variable with a block scope: declare it within a block.
Examples
When variables are declared using let and const in a block:

let post = false;
if (post) {
  let authorName = Maxwell;
  const articleTarget = 1000000;
console.log( `${authorName} wrote this post`)
 // β€”> Maxwell wrote this post 
console.log( `We hope this post would get ${articleTarget} likes`)
 // β€”> We hope this post would get 1000000 likes
}

console.log( `${authorName} wrote this post`) 
// β€”> ReferenceError authorName is not defined.  
console.log( `We hope this post would get ${articleTarget} likes`)
// β€”> ReferenceError articleTarget is not defined.

When variables are declared using var in a block

if (post) {
  var authorSister = Phoebe;

  console.log(`${authorSister} is a co-writer `)
 // β€”> Phoebe is a co-writer
}

console.log( `${authorSister} is a co-writer `)
 // β€”> Phoebe is a co-writer

Explanation

When variables are declared with let and const in a block, they can only be accessed inside the block in which they were declared. We say the let and const variables are block scoped.
On the other hand,variables declared with the var keyword are not blocked scoped. This means that they can be accessed outside blocks of code in which they are declared in.

Function scope

A variable with a function scope is a variable that can only be accessed or used within a function. To create a variable with a function scope: declare it within a function.
Examples
When variables are declared using let and const in a function

function functionScope (post) {
   let authorName = Maxwell;
   const articleTarget = 1000000;

   console.log( `${authorName} wrote this post`)
 // β€”> Maxwell wrote this post 
   console.log( `We hope this post would get ${articleTarget} likes`)
 // β€”> We hope this post would get 1000000 likes
}

   console.log( `${authorName} wrote this post`) 
// β€”> ReferenceError authorName is not defined. 
   console.log( `We hope this post would get ${articleTarget} likes`)
// β€”> ReferenceError articleTarget is not defined.

When variables are declared using var in a function:

function functionScope () {
   var authorSister = Phoebe;

   return () => console.log( `${authorSister} is a co-writer `)
 // β€”> Phoebe is a co-writer
}

console.log( `${authorSister} is a co-writer `)
 // β€”> ReferenceError authorSister is not defined.

Explanation

When variables are declared with let, const and var in a function, they can only be accessed inside the function in which they were declared. We say the variables are function scoped.

Lexical Scope

JavaScript allows us to nest blocks of code and functions. In doing so, the scopes of the blocks/functions are nested in one another. When there are two functions with one nested in the other, variables declared in the outer function can be accessed by variables declared in the inner function.
Take a look at the code below for better understanding.

function outerFunction () {
  let authorName = Maxwell;
  var authorSister = Phoebe;
  const articleTarget = 1000000;

  function innerFunction () {
     console.log( `${authorName} wrote this post`)
     // β€”> Maxwell wrote this post 
     console.log(`${authorSister} is a co-writer `)
     // β€”> Phoebe is a co-writer
      console.log( `We hope this post would get ${articleTarget} likes`)
     // β€”> We hope this post would get 1000000 likes
   };

innerFunction();
}

Explanation

In the example above, the variables declared in the outerFunction() are all accessible in the innerFunction because the innerFunction is nested in the outerFunction. This is what is referred to as lexical scope. NB the parent function (outerFunction) cannot access the variables declared in the nested function (innerFunction) because variables declared in the innerFunction have function-scope hence are inaccessible outside the innerFunction

function outerFunction () {
  function innerFunction () {
     let authorName = Maxwell;
     var authorSister = Phoebe;
     const articleTarget = 1000000;
   };

// trying to access the variables outside the innerFunction 
  console.log(authorName)
     // β€”> ReferenceError authorName is not defined.
  console.log(authorSister)
     // β€”> ReferenceError authorSister is not defined.
  console.log( articleTarget)
     // β€”> ReferenceError articleTarget is not defined.
}

Global Scope

A variable with global scope is a variable that can be accessed in any part of our code. Global scope variables are often declared independently (they do not sit within a block of code or within a function).
Examples

  let authorName = Maxwell;
  var authorSister = Phoebe;
  const articleTarget = 1000000;

Explanation

Notice that none of the three(3) variables were declared in either a block of code or a function hence the are globally scoped. All the three (3) variables declared can be used in any part of our code.

Overwriting values of globally scoped variables.

When a variable is redeclared within a block/function with the same identifier(name) but assigned a different value it overrides the globally scoped variable only within that block/function. Example

let authorName = Maxwell;
var authorSister = Phoebe;
const articleTarget = 1000000;

function outerFunction () {
// variables are redeclared and assigned  new values  
    let authorName = David;
    var authorSister = Janette;
    const articleTarget = 2;

    console.log (authorName); //-> David
    console.log (authorSister); //-> Janette
    console.log (articleTarget); //-> 2
 };

console.log (authorName); //-> Maxwell
console.log (authorSister); //-> Phoebe
console.log (articleTarget); //-> 1000000

Also:

let authorName = Maxwell;
var authorSister = Phoebe;
const articleTarget = 1000000;

function outerFunction () {
// variables are redeclared and assigned new values
    let authorName = David;
    var authorSister = Janette;
    const articleTarget = 2;

    console.log (authorName); //-> David
    console.log (authorSister); //-> Janette
    console.log (articleTarget); //-> 2
 };

let post = false;
if (post) {
console.log( `${authorName} wrote this post`)
 // β€”> Maxwell wrote this post 
console.log( `We hope this post would get ${articleTarget} likes`)
 // β€”> We hope this post would get 1000000 likes
}

Conclusion

In today's post we learnt that a variable can have one of four scopes in JavaScript: block scope, function scope, lexical scope and global scope. Variables declared with let and const are block and local scoped. Whereas variables declared with var are only local scoped. Lexical scoping works in only one direction: only the nested functions and blocks can access the variables of their parent.

That’s a wrap! I appreciate you reading this, and I hope you learnt something today. Post a comment and share your thoughts. Click the follow button for more on JavaScript and other technologies in web development.

Β