DEV Community

Code Craft-Fun with Javascript
Code Craft-Fun with Javascript

Posted on • Originally published at code-craft.hashnode.dev on

Variable Scope and Scope Chain in Javascript

Scope and Scope Chaining

In Javascript, scope refers to the accessibility or visibility of variables , functions, and objects in a particular part of your code during runtime. Understanding how scope works is crucial for writing efficient and bug-free Javascript code. In this blog post, we'll explore the concept of scope and scope chaining along with detailed code examples.

What is Variable Scope?

Variable Scope determines the accessibility and lifetime of variables and parameters. Javascript has two main types of scope:

  • Global Scope
  • Local Scope

Global Scope

Globally scoped variables can be accessed from anywhere in the code, including within functions. These are the variables that are defined outside of any function. Consider an example below:



var message = 'Hello, I am globally available!';

function printMessage() {
  console.log(message);
}
function showMessage() {
  alert(message)
}

printMessage(); // Output: Hello, I am globally available!
showMessage(); // Output: alert will be displayed on the screen showing the text "Hello, I am globally available!"



Enter fullscreen mode Exit fullscreen mode

In this example, variable message is defined outside the printMessage() & showMessage()function and can be accessed within the function, so message has a global scope.

Local Scope

Variables declared inside a function have local scope and can only be accessed within that function. Consider an example below:



function printMessage() {
  var message = 'Hello, World!';
  console.log(message);
}

printMessage(); // Output: Hello, World!
console.log(message); // Error: message is not defined



Enter fullscreen mode Exit fullscreen mode

You got an idea now, right? The message variable is declared in the printMessage() function and cannot be accessed outside of it. Therefore, the console.log(message) will throw an error Uncaught ReferenceError: message is not defined

Scope Chain

What if we define a function inside a function and access the global variable inside the inner function? Yes, as you know we can do so as a global variable is available anywhere in the code, we can access it in the inner function as well.

When a variable is accessed, Javascript first searches for it in the current scope, and if it's not found, it moves up the scope chain until the variable is found or the global scope is reached.

This hierarchical structure determines the order in which Javascript looks for variables is called a Scope Chain. Simple!

Let's explore the scope chain with a nested function example:



var globalVariable = "Hello"
function outer() {
  var outerVariable = 'My';

  function inner() {
    var innerVariable = 'World';
    console.log(globalVariable + ' ' + outerVariable + ' ' + innerVariable);
  }

  inner(); // Output: Hello My World
}

outer();



Enter fullscreen mode Exit fullscreen mode

In this example, the inner() function is nested inside the outer() function. The inner function has access to globalVariable, outerVariable and innerVariable . When inner() is called, it first checks for the globalVariable within its own scope. Since it's not found, it looks in the outer scope in outer() function and then it finds it in the global scope. Once it gets the globalVariable it checks for outerVariable variable in the same way. At last it checks for innerVariable which is already in its own scope. And finally logs the concatenated string.

Block Scope with let & const

Before ECMAScript 6 (ES6), Javascript only had function scope. However, ES6 introduced block scope with the let and const keywords. Variables declared with let and const have block scope, meaning they are only accessible within the block ({}) in which they are defined.



function printMessage() {
  if (true) {
    let message = 'Hey, Block!';
    console.log(message);
  }

  console.log(message); // Error: message is not defined
}

printMessage();



Enter fullscreen mode Exit fullscreen mode

In this example, message is defined within the if block and can only be accessed within that block. Attempting to access it outside the block results in an error.

Tips & Tricks

As we know that var is a function scope it can have some weird effects on your code if not used properly. Consider an example below:



// 1. variable can be redeclared in the same scope!
var message = "Hi";
var message = "Hello"; 
console.log(message) // Output : Hello

// 2. var do not maintain the block scope. Can be changed outside of the block in whcih it was declared.
if ( message ) {
    var newMessage = "Hey";
}
newMessage = "Bye";
console.log(newMessage) // Output: Bye

// 3. variables can be declared without using the var keyword
greet = "My greetings";
console.log(greet) // Output: My greetings



Enter fullscreen mode Exit fullscreen mode

To avoid this behaviour of variable declared with the var keyword, use let & const instead. They are stricter than var as they are blocked scope.

Strictness : var < let < const

Conclusion

By properly managing scope, you can avoid variable conflicts, improve code efficiency, and ensure that your code behaves as expected. So, make sure to grasp the concept of scope and leverage it to your advantage in your Javascript projects.

Top comments (0)