Home » Scope in JavaScript

Scope in JavaScript

Scope in JavaScript

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. In simple terms, we can say How our program organised and accessed the variable “where we can access”.

Lexical Scope in JavaScript

lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

There are two kinds of scope — Global scope and Local scope.

Global Scope in JavaScript

Variables defined outside a function are in the global scope. Also, there is only one Global scope throughout a JavaScript document. Once you’ve declared a global variable, you can use that variable anywhere in your code, even in the function

Local Scope in JavaScript

Variables defined inside a function are in the local scope. And they have a different scope for every call of that function. Also, Each function when invoked creates a new scope. So there is a Function scope also.

Focus on outer and inner function. every function has its local scope.

let piyush = "Good student"; // Global scope

function kalpesh(){ // functional scope
   var stu = "has good communication";
   console.log(piyush); //
   console.log(stu); //
}
// console.log(stu); //
kalpesh();

{ //blockscope (if else)
   var geekster = "an edtech";
   console.log(geekster);
}
console.log(geekster);
// let fun and block scope
// var is function scope not block scope   
JavaScript

Let’s discuss the scope of let, const, and var.

function-scope.png

Function scope: Anything declared inside a function is inaccessible from the outside of the function.

Block scope: IF you declare something inside if/for/while block, it creates a block scope. Anything inside a curly brace is a block scope. But remember that only let and const can be used to create block scope. Using var will not create a block scope.

// window object
function fun(){
    if(true){
         var foo = "foo"
         const bar = "bar"
          //let behavior also similar
}
console.log(foo)
console.log(bar) // ReferanceError
}
fun()
JavaScript

here variable foo is accessible because var is function scope.

All scopes in JavaScript are created with Function Scope only, they aren’t created by for, while loops or expression statements like if and switch. Variables defined inside of a block statement will remain in the scope they were already in.

That’s all in scopes. Hope you like it.

Scope Chain

Now you may ask what is Scope Chain and How it affect code?

Scope chains establish the scope for a given function. Each function defined has its nested scope, and any function defined within another function has a local scope that is linked to the outer function — this link is called the chain.

Calling a function doesn’t affect the scope chain. How? Let’s see

let global = 'global';
function first(){
    let foo = 'first'
    function second(){
    let bar = 'second' 
    third() 
     }
   second()
}
function third(){
   let temp = 'third'
   console.log(foo) //ReferenceError
   console.log(bar) // ReferacnceError
   console.log(global,temp)
}
first()
JavaScript

only global and temp variables accessible. why?

To access “foo” and “bar” we have to scoped or define the third function into the second function.

Conclusion

Understanding scope is crucial for effective JavaScript programming. It influences how and where we can access variables and functions, impacting code organization, maintainability, and security. Lexical scoping, the distinction between global and local scope, and the nuances of var, let, and const play significant roles in shaping JavaScript’s behavior. The scope chain and closures further demonstrate the power and flexibility of function scoping, enabling patterns and practices that are foundational to modern JavaScript development. By mastering these concepts, developers can write cleaner, more efficient, and error-free code.

Frequently Asked Questions

Q1. What is scope in JavaScript?

Ans: Scope in JavaScript refers to the context in which variables and functions are accessible. It determines the visibility of variables to different parts of your code.


Q2. How does lexical scope work in JavaScript?

Ans: Lexical scope means that the accessibility of variables is determined by the position of variables within the nested function scopes: variables declared outside a function are globally accessible, while those declared inside a function are only accessible within the function and its nested functions.


Q3. What is the difference between global scope and local scope?

Ans: Global scope refers to variables that are accessible from anywhere in the code, whereas local scope refers to variables that are accessible only within the function they are declared in or its child functions.


Q4. Can you explain function scope and block scope?

Ans: Function scope: Variables declared inside a function are accessible only within the function, not outside.
Block scope: Introduced with ES6, let and const allow for block-level scoping, meaning variables are confined to the block (denoted by curly braces {}) in which they are declared.


Q5. How do var, let, and const differ in terms of scope?

Ans: var declares variables with function scope or global scope if declared outside a function.
let and const declare variables with block scope, meaning they are limited to the block in which they are defined.