ES6 introduced following scopes for the variables and functions

  • Global
  • Module
  • Functional
  • Block scopes

Let’s discuss each scope with example

How to define variables in Global Scope with ES6?

Scopes in Javascript are nested in the order Global -> module-> functional -> block scopes.

Global scope is outermost root place. Variables declare in root place using let, var are called global variables.

Object variables are stored in global are called global objects.

You can access global variables using globalThis in ES6.

This sets the variable from a module into a global scope.

You can access the variable directly with name anywhere as seen below

function setGlobalVariable(s) {
    globalThis.name = s
}

setGlobalVariable("john")
console.log(name)

Another way variable declared with var in the outer function also called global scope.

globalThis does not work in Nodejs,

ES6 module scope

Variables private to a module or file. If you want to use the variable outside module, you have to declare with export Module1.js:

export let variable1=123

In Module2.js

import { variable1 } from './Module1.js';
console.log(variabl1) // 123

Function Scopes in ES6

variable declared with var inside a function are function scope

Block Scopes in ES6

block scopes also called lexical scoping. variables declared in Block scopes comes in

  • Inside functions
  • Inside blocks declared with curly braces { }