DEV Community

Cover image for Scope in Javascript
Ifeanyi Chima
Ifeanyi Chima

Posted on • Edited on

Scope in Javascript

Today, we are going to try to understand scope in javascript.

In Javascript, Scope refers to the current context of code, which determines the accessibility of variables to javascript. Which means variables are accessible only in the environment in which they were created, and are also accessible by their children.

Image description

There are two types of scope, global and local scope.

Global scope

Global scope, it is also known as window object. It is the entire javascript execution environment.

Any variable defined in the global scope will be accessible
throughout the entire program.

Any variable assigned without an explicit scope (using the var, let, or const keywords) automatically become global variables. The same is true for functions. reference

// index.js

const myName = "Mark Zuckerberg" // global scope

console.log(myName) // Mark Zuckerberg

Enter fullscreen mode Exit fullscreen mode

Image description

Local scope

Local scope is also known as function scope, if you define variables inside a function, they are only accessible within that particular function, they can not be accessed outside of that function.

// index.js

function getAge() {
   const myAge = 34;
   console.log(myAge); // 34
}

console.log(myAge) // ReferenceError: myAge is not defined

Enter fullscreen mode Exit fullscreen mode

scope chain

Javascript uses a scope chain to find variables accessible in a certain scope. Which means when a variable is referred to, Javascript will look for it in the current scope and continue to the parent scope until it reaches the global scope.

// global scope
const a = 10; // accessible to everyone

const outerFunc = () => {
  var b = 20;  // a and b is accessible
  console.log(a, b);

  const innerFunc = () => {
      var c = 30;  // a, b and c is accessible
      console.log(a, b, c);
  }

  innerFunc();
}

outerFunc();

Enter fullscreen mode Exit fullscreen mode

To run the codes node index.js

Thank You, please follow me

linkedin.com/in/ifeanyi-thankgod-chima/
https://twitter.com/ifeanyiTchima

Buy Me A Coffee

Top comments (0)