📒
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript  — this keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists — 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (‘ ’) and double quotes (“ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • What are scopes?
  • Why should we care to learn it?
  • What are the types of scope?
  • Global Scope and Local Scope
  • Lexical Scope
  • Block Scope
  • Public and Private scopes

Was this helpful?

JavaScript Scopes

PreviousClean Code for JS VariablesNextScope (Chain) Visualized

Last updated 5 years ago

Was this helpful?

What are scopes?

The scope is the accessibility of variables, functions, or objects in some particular part of your code during runtime.

They came into existence when the was applied in programming language designs.

Why should we care to learn it?

They provide some level of security to your code, i.e are only used when they are really needed.

Scoping parts of your code help improve efficiency, track and reduce bugs.

It also solves the naming problem when you have variables with the same name but in different scopes, so reduce namespace collision.

What are the types of scope?

  1. Global and Local

  2. Lexical

  3. Block

  4. Public and Private

Let see each of them one by one with examples.

Global Scope and Local Scope

Any variable declared outside of a function belongs to the global scope and is therefore accessible and can be altered from anywhere in your code.

Variables defined inside a function are in the local scope. They have a different scope for every call of that function. This means that variables having the same name can be used in different functions. This is because those variables are bound to their respective functions, each having different scopes, and are not accessible in other functions.

New functions = new local scope — that’s the rule.

// Gobal
var mouse = "Mouse";function test1() {
  // Local
  var name = "Cat";
  console.log(name);
}function test2() {
  // Local
  var name = "Dog";
  console.log(name);
}test1();
test2();console.log(name);

Lexical Scope

When a function within another function, the inner function has access to the scope in the outer function, this is called Lexical Scope — also referred to as Static Scope as it may only be called (referenced) from within the block of code in which it is defined.

JavaScript starts at the innermost scope and searches outwards until it finds the variable/object/function it was looking for.

The important thing to remember is that the Lexical scope does not work backward. i.e we cannot access comments variable in SocialMedia function and in the Platform function in above example.

Block Scope

Block statements like if and switch conditions or for and while loops and {} unlike functions, don't create a new scope. Variables defined inside of a block statement will remain in the scope they were already in.

// Gobal
var name = "Mouse";{
  // Local
  var name = "Cat";
  console.log(name); // Cat
}console.log(name); // Mouse

Let see an interview question around it (mix of the execution context, closures, and scopes)

for (var i = 0; i < 3; i++) {
  setTimeout(function() { console.log(i); }, 1000 + i);
}

Above will output 3,3,3 as each time the same variable value is assigned.

In the first iteration, the console.log(i) will be added to stack, event loop detects it has delay, it sent to the event queue and this happens 2 more times and finally when event loop start picking them one by one to execute the final value of var i is 3 due to last i++ and since the scope of variable is same the value of each becomes 3 while its return.

However, ECMAScript 6 introduced the let and const keywords. These keywords can be used in place of the var keyword and the let and const keywords support the declaration of local scope inside block statements.

if we change var i to let i, let see the difference now.

for (let i = 0; i < 3; i++) {
  setTimeout(function() { console.log(i); }, 1000 + i);
}

Above will output 0,1,2 as each time a new scope for a variable is created.

Public and Private scopes

Wrapping functions from the public (global) scope save them from vulnerable attacks. But in JavaScript, there is no such thing as public or private scope. However, we can emulate them though.

(function () {   
    var test = function () {
     // do some stuff here   
    }; 
})(); 
// The parenthesis at the end of the function tells the interpreter to execute it as soon as it reads it without invocation.test(); // Uncaught ReferenceError

A design pattern called module pattern can be used to create such functionality also.

Private and public scopes in javascript

The return statement of the modulePattern contains our public functions. The private functions are just those that are not returned. Not returning functions makes them inaccessible outside of the modulePattern namespace. But our public functions can access our private functions which make them handy for helper functions.

principle of least privilege