Javascript Variable Scopes

Javascript Variable Scopes

Introduction:

This article is first part of very important topics in javascript which covers the basics of programming in javascript.

In this article, we will discuss the fundamental topic of scope in javascript. We will cover different types of variable scopes available in javascript with some examples. We will also briefly cover new variable declaration keywords introduced in ES2016.

But first, we will cover difference between variable declaration and assignment. Let’s look into the difference between them.

Variable Declaration vs Assignment:

A variable declaration simply tells the interpreter that a variable exists. By default, it is initialised as undefined.

var studentName;
console.log(studentName);  //Prints “undefined”

Thing to note here:

  • We have declared a variable studentName. By default it is initialised as undefined.
  • It does not throw ReferenceError – studentName is not defined because it is initialised by default.

Variable assignment refers to assignment of value to the variable.

studentName = 'John Doe';

We can both declare and assign value to a variable in single line:

var studentName = 'John Doe';

Scope:

Scope in javascript refers to the current context of code. It determines the accessibility (visibility) of variables.

In javascript, there can be following types of scopes:

  1. Global Scope
  2. Local Scope or Function Scope
  3. Block Scope

Global Scope

Any variable that is declared outside a function or block is considered in global scope. The variables in global scope can be accessed from anywhere.

var studentName = 'John Doe';
function printName() {
    console.log(studentName);
}
printName();  //Prints  ‘John Doe’
var studentName = 'John Doe';
function printName() {
        studentName = 'Elizabeth';   
        console.log(studentName);
}
printName();  //Prints  ‘Elizabeth’

Things to note here:

  • In above example, we have defined a variable studentName which is outside of any function. Therefore, this variable is in global scope and it can be accessed anywhere in above code.
  • Declaring global variable is discouraged in javascript because it can be accessed anywhere in code and thus any piece of code can update the value of this variable.

Let’s move to next part which is “Local Scope”.

Local Scope

Variables declared within a javascript function are in local scope. They can only be accessed from within that function.

function printName() {
    var studentName = 'John Doe';
    console.log(studentName);  
}
printName();  // Prints ‘John Doe’
console.log(studentName); //Reference error: studentName is not defined

Things to note here:

  • We have defined a variable studentName inside the function printName. So, this variable is in local scope or locally scoped to the function printName. This cannot be accessed outside the function printName.
  • If we try to access it outside function printName, it throws reference error: variable is not defined

Variables declared with “var” keyword can only be either in global scope or in local scope/function scope. Then, here comes another type of scope which is introduced in ES2016 i.e. block scope. Let’s look at this block scope.

Block Scope

Variables defined within any block (within pair of curly braces) such as if, for, while etc. are considered in block scope. These cannot be accessed from outside that block.

“var” cannot have block scope, therefore, in ES6 two new variable assignment keywords are introduced “let” and “const”. These can be used to implement block scope.

{
    let studentName = 'John Doe';
    var collegeName = 'MIT';

    console.log(studentName);    // Prints ‘John Doe’
    console.log(collegeName);    // Prints ‘MIT’
}
console.log(collegeName);    // Prints ‘MIT’
console.log(studentName);   // ReferenceError: studentName is not defined
{
    const age = 30
    console.log(age);  //Prints 30
}
console.log(age);   //ReferenceError: age is not defined

Things to note here:

  • We have declared variable studentName using let keyword inside curly braces. Therefore, the variable studentName is block scoped to nearest pair of curly braces i.e. it cannot be accessed outside these curly braces.
  • If we try to access studentName outside their block, it throws “ReferenceError: studentName is not defined”
  • Similarly, in second example, we have defined a variable age using keyword const inside curly braces. It is also block scoped to those curly braces and cannot be accessed outside that block.

Summary:

  • A variable declaration simply tells the interpreter that a variable exists
  • A variable is initialized as “undefined” by default.
  • Variable assignment refers to assignment of value to the variable.
  • Three types of variable scopes: global scope, local scope or function scope and block scope

That’s it for now. Thank you for taking time to read this article. Do provide feedback and comments. I’ll cover more topics like hoisting, difference between var, let and const in upcoming posts. Keep following!