DEV Community

Cover image for Day 99/100 Scope
Rio Cantre
Rio Cantre

Posted on • Originally published at dev.to

Day 99/100 Scope

banner

The scope is defined as a specific portion of the code. There are three types of scope in Javascript:

  • Global scope - When a particular variable is visible (can be used) anywhere in the code. Such a variable is generally called as Global variable.

  • Function scope - When a particular variable is visible (can be used) within a particular function only. Such a variable is generally called as Local variable.

  • Block scope - When a particular variable is visible (can be used) within a pair of { . . . } only.

The JavaScript language is constantly improving. One of these updates introduces a new type of scope, called Block scope.

var a = 1;
function x() {
var b = 2;
function y() {
    var c = 3;
    function z() {
    var d = 4;
    }
    z();
}
y();
}

x();
Enter fullscreen mode Exit fullscreen mode

The variable c is defined inside function y(), so it's accessible only inside function y(). This means it can be printed anywhere inside function y(), as well as inside any functions declared inside function y().The inner functions y() and z() have access to their own local variables, the variables defined inside the functions they were also defined in (x() and y() functions respectively), and any global variables.

Scope Recap

  • If an identifier is declared in global scope, it's available everywhere.

  • If an identifier is declared in function scope, it's available in the function it was declared in (even in functions declared inside the function).

  • When trying to access an identifier, the JavaScript Engine will first look in the current function. If it doesn't find anything, it will continue to the next outer function to see if it can find the identifier there. It will keep doing this until it reaches the global scope.

  • Global identifiers are a bad idea. They can lead to bad variable names, conflicting variable names, and messy code.

Code Snippets

var row = 0;  // initial value of the row
var seat = 0; // initial value of the seat within a row

for (row = 0; row <= 25; row++){
    for(seat = 0; seat <= 99; seat++){
        console.log(row+"-"+seat);
    }
}
Enter fullscreen mode Exit fullscreen mode

Summary

Happy Hacking!

Resource

Top comments (0)