riocantre

Rio Cantre

Posted on December 23, 2021

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

πŸ’– πŸ’ͺ πŸ™… 🚩
riocantre
Rio Cantre

Posted on December 23, 2021

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

Sign up to receive the latest update from our blog.

Related

Day 100/100 Reverse Function
100daysofcode Day 100/100 Reverse Function

December 24, 2021

Day 99/100 Scope
100daysofcode Day 99/100 Scope

December 23, 2021

Day 98/100 Objects in Code
100daysofcode Day 98/100 Objects in Code

December 22, 2021

Day 97/100 Donuts to Code
100daysofcode Day 97/100 Donuts to Code

December 21, 2021

Day 96/100 Data Types
100daysofcode Day 96/100 Data Types

December 20, 2021