Demystifying JavaScript Scopes: A Deep Dive into var, let, and const

Demystifying JavaScript Scopes: A Deep Dive into var, let, and const

Is JavaScript Interpreted or Compiled Language?

First Let us Understand, what is interpreted and what is Compiled Language?

Interpreted Language - the source code will be read and directly executed, line by line.

Compiled Language - the source file typically will be “compiled” to machine code (or byte code) before being executed.

Now Coming to JavaScript, It is neither Purely Interpreted nor Purely Compiled Language.

Let's take an example:

  • In the above example, the execution stops in first line itself.

  • So, maybe it's Compiled...? In this line of code It's acting as Compiled Language.

Let's take another example:

  • In this example, the first line is executed and it throws error in the second line.

  • In this line of code, It's acting as Interpreted language.

So, we can't say for sure JavaScript is Compiled or Interpreted, but it’s a matter of perspective and implementation, I guess.

So, What happens when JS program is run?

  • When a JS program is ran, a global execution context is created.

  • The execution context is created in two phases. i.e. the JS code execution is done in two phases.

  • Memory creation phase (Parsing phase)- JS will allocate memory to variables and functions.

  • Code execution phase.

Read more about how JavaScript works Internally.

In Code Execution Phase, JavaScript reads the whole code and for every variable and function, it allocates a particular scope.

What do we mean by Particular Scope?

It means we have different type of scopes. There are mainly three types of scopes.

  1. Global Scope

  2. Function Scope

  3. Block Scope

Global Scope - In JavaScript, the global scope refers to the outermost scope, encompassing the entire JavaScript runtime environment. Any variable or function declared outside of any function or block is considered to be in the global scope.

  • If we define a variable in Global Scope, it is accessible everywhere.

  • Variables declared in the global scope have a lifetime equal to the runtime of the web page or application. They exist as long as the page is loaded in the browser or until explicitly removed.

  • Variables in the global scope can be accessed and modified from any part of the code, whether it's within functions, blocks, or nested scopes. This makes global variables powerful but also potentially risky, as they can lead to unintended side effects.

  • In the browser environment, global variables are attached to the window object. This means you can access a global variable as a property of the window object.

  • In the above example, the variable name is global scope. It can be accessed from anywhere.

  • This is only true when the variable is accessed after initialising. we'll understand what happens if we access before initialising in future. For now let's just assume Global variable can be used and accessed anywhere in the code after initialising.

Function Scope - Function scope in JavaScript refers to the scope of variables defined within a function. When a variable is declared inside a function using the var, let, or const keywords, it is said to have function scope.

  • In the above example, we can observe that the variable x can be accessed only inside the function. It is known as function scope.

  • We will discuss more about this function scope and how this works for var, let and const .

Block Scope - Block scope in JavaScript refers to the scope of variables defined within a block of code. A block is typically defined by a pair of curly braces {} and can include statements, control structures (like if statements and loops), and even functions.

  • Variables declared with let and const have block scope, meaning they are only accessible within the block in which they are defined.

  • i.e. Blocks only scope let and const declarations, but not var declarations.

    JS

  • In the above Image 1 - var can be accessible even if it's in the block scope.

  • In image 2 - const is not accessible outside the scope.

  • Block scope helps prevent unintended variable hoisting and redeclaration issues.

  • It allows for more precise control over variable lifetimes, reducing the risk of naming conflicts.

Now Let's Understand about var, let and const :

Var :

  • The var statement declares function-scoped or globally-scoped variables, optionally initializing each to a value.

  • Variables declared with var are hoisted to the top of their scope during the compilation phase. Means, the variables which are declared with var keyword, automatically allocated the value undefined in the parsing phase.

  • Variables declared with var can be reassigned and redeclared within the same scope without any issues.

      function x(){
          var y = "Kohli";
      }
      console.log(y) // gives an error because var is function scope.
      // it gives error as y is not defined
      // because y is present in function scope of x().
      // In outer environment there is no y is present, so it gives an error.
    
      var x = 5;
      var x = 10; // No error, redeclaration is allowed
    
      var x = 1;
      if (x === 1) {
        var x = 2;
        console.log(x);
        // Expected output: 2
      }
      console.log(x);
      // Expected output: 2
    

Let :

  • The let declaration declares re-assignable, block-scoped local variables, optionally initializing each to a value. Let us understand this by taking an example.

      let x = 1;
      if (x === 1) {
        let x = 2;
        console.log(x);
        // Expected output: 2
      }
      console.log(x);
      // Expected output: 1
    
  • In the above example, the code in the first line let x = 1 is totally different from code in the third line let x = 2

  • the value of x in if block can be accessed only in the if block itself. we cannot access it outside the if block.

  • Where as for var the case is different. Let's tackle this with an example.

  • In the above first code snippet, as we discussed let is block scoped, therefore, its not even present in the outer environment.

  • But in terms of using var , it is not block scoped, so we can access it even if its in the block scope.

  • In the above example code snippet, let acts as a block scope although its inside function because function also acts as a block.

  • So, we can't access the variables outside the function scope if they are declared with keyword let

Const :

  • const is block-scoped, just like let.

  • Variables declared with const cannot be reassigned after initialization.

  • the only difference between let and const are variables declared with const cannot be reassigned after initialization.

      const z = 5;
      z = 10; // Error: Assignment to constant variable
    
  • const requires initialization at the time of declaration. It cannot be declared without a value.

      const pi; // Error: Missing initializer in const declaration
    
  • While a variable declared with const cannot be reassigned, the properties of an object assigned to a const variable can be modified.

      const person = { name: 'John' };
      person.age = 30; // Allowed, modifying object property
    

Use Cases :

  • Use var when you need function scope and don't mind hoisting.

  • Use let when you need block scope and the variable might be reassigned.

  • Use const when you need block scope and the variable should not be reassigned.

In modern JavaScript development, it's recommended to use let and const over var due to the more predictable scoping behavior they provide. const is particularly useful for declaring constants or values that should not be reassigned. However, the choice between let and const depends on whether reassignment is expected in your code.

In conclusion, mastering JavaScript scopes and variable declarations is pivotal for writing efficient and maintainable code. By understanding the nuances of var, let, and const, you've taken a significant step towards becoming a more proficient JavaScript developer. As you continue your coding journey, I encourage you to apply these concepts in your projects. Experiment with different scenarios, challenge yourself, and don't hesitate to explore more advanced topics in JavaScript. The world of web development is dynamic, and your knowledge will be the key to unlocking new possibilities. Thank you for joining me on this exploration of JavaScript scopes and variables. If you have questions or thoughts to share, feel free to reach out.

Happy coding!