Variable Scoping in JavaScript

In programming generally, the scope of a variable is the part of the program where the variable is visible and accessible, JavaScript makes use of Lexical Scoping, which is also known as Static Scoping. The aim of creating a variable has a significant role to play in where it should be accessible.

JavaScript has two scoping types known Global Scope and Local Scope. Without much ado let's jump to the theoretical and practical explanations of these two concepts.

Global Scoping: As the name implies, variables declared globally (not any code block) are accessible anywhere in the program. let look at this code snippet for more elaboration

 let fatherName = "Usman"

function firstChild(){
    console.log(fatherName)
    //Out is Usman
}

function secondChild(){
     console.log(fatherName)
     //Output is Usman
}

From the code snippets above both firstChild and secondChild functions can access the variable fatherName because is globally declared.

Local Scope: Variable declared in a code block is known as local scope because is only accessible for the code within the block is declared. Using the same example above, let say the firstChild() function declare a variable inside it called firstDaughterName = "Fatimat". This variable will not be accessible to secondChild() function, why because the firstDaughterName is declared within firstChild() function block and is only accessible there. Let experiment this on code snippets.

 let fatherName = "Usman"

function firstChild(){
    let firstDaughterName = "Fatimat"
    console.log(`My first daughter name is ${firstDaughterName}`)
    //My first daughter name is Fatimat
}


function secondChild(){
     console.log(`My first daughter name is ${firstDaughterName}`)
    // Uncaught ReferenceError: firstDaughterName is not defined 
}

From the output you see that the secondChild() function throws an error because the variable firstDaughterName is not global and not also declared within it block.

Conclusion

Before declaring a variable is important you know its purpose, which will help you to decide if the variable should be global or local. If you will need the variable in two or more code blocks, then it should be global, otherwise use declare the variable within the code block.