Home JavaScript Scopes in JavaScript

Scopes in JavaScript

by anupmaurya
6 minutes read
Scopes in JavaScript

In this article, you’ll learn about Scopes in JavaScript and it’s a very important concept as help us to understand which part of a program where it is available for use.

Scope is a way to define the accessibility of variables. JavaScript has evolved over time in accordance with the principle of least accessibility. In 2015, it introduced let and const which enables block scoping.

From JavaScript’s perspective, scope is a way to clearly define the execution context. It will reduce the clutter during development and execution.

So, In one sentence we can define scope as “the area in code from where a variable can be accessed.” or Scope refers to the availability of variables and functions in certain parts of the code.

Types of Scopes in JavaScript

JavaScript has 3 types of scope:

  • Block scope
  • Function scope
  • Global scope

1.Block Scope

ES6 introduced let and const variables, unlike var variables, they can be scoped to the nearest pair of curly braces. That means, they can’t be accessed from outside that pair of curly braces.

{
  let greeting = 'Hello JavaScript!';
  var lang = 'JavaScript';
  console.log(greeting); // Prints Hello JavaScript!
}
console.log(lang);   // Prints JavaScript
console.log(greeting);   // Uncaught ReferenceError: greeting is not defined

You can see that var variables can be used outside the block, that is, var variables are not block scoped.

2.Function Scope

Variables declared inside a function is inside the local scope. They can only be accessed from within that function, that means they can’t be accessed from the outside code.

function greet() {
   let greeting = 'Hello JavaScript!';
  console.log(greeting);
}
greet();  // Prints Hello JavaScript!
console.log(greeting);  // Uncaught ReferenceError: greeting is not defined

3.Global Scope

Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope. The variables in global scope can be accessed from anywhere in the program.

let message = "hello JavaScript"

The variable message is defined in the global scope. We can access it anywhere in the document.

Global variables are available for the lifetime of the application.

There are some other scope as well, which is build on basically Global Scope, Function Scope, and Block Scope.

Nested Scope

Just like functions in JavaScript, a scope can be nested inside another scope.

var name = 'Anup Maurya';
function greet() {
  var greeting = 'Hello';
  {
    let lang = 'JavaScript';
    console.log(`${lang}: ${greeting} ${name}`);
  }
}
greet();

As In the above example, You can see 3 scopes nested within each other. First, the block scope (created due to the let variable) is nested inside the local or function scope which is in turn nested inside the global scope.

Lexical Scope

Lexical Scope (also known as Static Scope) literally means that scope is determined at the lexing time (generally referred to as compiling) rather than at runtime.

A 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.

var str="JavaScript";

const myString = () => {
    console.log(str);
}
myString();

So, the myString() function is accessing the global variable str which is defined before method function myString is called. This is called due to lexical scoping in JavaScript.

Why does scope exist?

Scopes can create execution context for JS engine. For example, when the engine starts executing a function, all the variables defined inside the function are allocated to memory. Once the function is done executing, the variables are destroyed. This will keep the memory clean and provides a proper execution context to the JS engine.

This will also help developers easily deal with bugs since codes can be looked at in isolated pieces. It will also take care of variable naming issues since we can repeat the same variable names in different scopes.

Variables declared in global scope should be minimum, as global scope variables are in the memory until application closes. Make sure any variable is only within the necessary scope. Principle of least accessibility should be practiced.

That’s all for this article and with that, it’s a wrap! I hope you found the article useful. Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

Ta da! Having fun learning JavaScript!! ❤️

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.