JavaScript
  • JavaScript Introduction
  • JS Engine
  • V8 Engine
  • First-class function
  • Optimized Code
  • Call Stack & Memory heap
  • Single Thread
  • JavaScript RunTime
  • Nodejs
  • Context and Environment
  • Hoisting
  • Functions
  • Arguments
  • Variables
  • Scope
  • IIFE
  • this
  • call(), apply() and bind()
  • currying
  • Types
  • Type Coercion
  • Functions as Object
  • HOF (Higher Order Function)
  • Two pillars of Javascript
  • Closures
  • Prototypal Inheritance
  • OOP and FP
  • OOP
    • 4 principles of OOP
  • FP
    • Pure function
    • Imperative vs Declarative
    • Immutability
    • HOF and Closures
    • Currying
    • Partial Application
    • Compose and Pipe
  • Composition vs Inheritance
  • OOP vs FP
  • JS working
  • Promises
  • Async Await
  • ES5 - ECMAScript 2009
  • ES6 - ECMAScript 2015
  • ES7 - ECMAScript 2016
  • ES8 - ECMAScript 2017
  • ES9 - ECMAScript 2018
  • ES10 - ECMAScript 2019
  • ES11 - ECMAScript 2020
  • ES12 - ECMAScript 2021
  • JOB Queue
  • Promises Execution
Powered by GitBook
On this page

Was this helpful?

Scope

Where can i access my variable in my code(where is the variable in my code).

Function Scope:

  • Every Execution context has a link with the outer environment or link with its parent environment.

var name = "Vijay";
function sayName() {
    console.log(name); // Vijay
    var nickName = "Deepak";
    console.log(nickName); // Deepak
    return function subName() {
        console.log(name); // Vijay
        console.log(nickName); // Deepak
        var nickName2 = "Vishnu";
        console.log(nickName2); // Vishnu
    }
    console.log(nickName2); // Reference Error: nickName2 id not defined
}

var myNameFn = sayName();
myNameFn();

we can access the parent variables from any of its child, but not from parent to child.

Note: As mentioned in the optimized code topic not to use eval() and with in JavaScript, it may confuse the JavaScript engine regarding the scope while optimizing the code, some times it may de-optimize the code.

Block Scope:

A variable created inside a curly braces "{ }", cannot be accessible outside.

  • Block scope is introduced in JavaScript as ES6.

  • variables should be declared with "let" or "const" key word.

Function VS Block Scope:

// Function Scope
function alpha() {
    var message = "Hello";
}
console.log(message); // Reference Error: message is not defined
if (5>1) {
    var message = "Hello";
}
console.log(message); // Hello

// Block Scope
if (5>1) {
    let message = "Hello";
    const name = "John";
}
console.log(message); // Reference Error: message is not defined
console.log(name); // Reference Error: name is not defined
PreviousVariablesNextIIFE

Last updated 5 years ago

Was this helpful?

Global/Function Lexical Environment of the Example above