Difference between var, let, and const in JavaScript

 

INTRODUCTION

All JavaScript developer must encounter variables and how to declare variables them in every line of code they write. In JavaScript, there are three ways to declare a variable they are using: var, let, and const keyword. The 3 keywords may seems similar but, each has its unique behavior, and understanding these differences is crucial for writing clean, bug-free code.

In this tutorial, we will explore the differences between var, let, and const with examples to help you choose the right one depending on the situation. There are issues with declaring variables using var and that issue was what lead to the introduction of the let and const keyword.

Var

This is the old way of declaring a variable. It was introduced in the earliest versions of JavaScript, var was the only way to declare variables before ES6 (ECMAScript 2015).

Characteristics of var

  • Function-scoped: var is only scoped within the function it’s declared in, not the block (like if, for, or while blocks). When we say "var is function-scoped, not block-scoped," it means that when you declare a variable with var inside a block like an if, for, or while statement, it doesn’t stay limited to that block. Instead, the variable becomes available throughout the entire function that contains it — or globally if it's not inside a function.
  • Hoisted: Variables declared with var are hoisted to the top of their scope. This means they can be referenced before they are actually declared (though the value will be undefined until the line where they are assigned). In simple term it means you  use a variable before you declare it  and the program will not throw an error. It will only print undefined.
  • Can be re-declared and updated: You can declare the same variable multiple times without any error.

Example:

Function-Scoped

<script type="text/javascript">
        function  blogName(){
            if(true){
                var name="Easy Code"; //Available through out the program.
                document.write(name) //Displayed inside the block
                document.write("<br>")
            }
             document.write(name) // Displayed outside the if block
        }
        blogName() //Invoked function
 </script>

Hoisted

<script type="text/javascript">
        function  blogName(){
            document.write(name);//output undfined
            var name="Easy Code";
            document.write("<br>");
            document.write(name);// output Easy Code
        }
        blogName() //Invoked function
    </script>

Can be re-declared and updated

<script type="text/javascript">
        function  blogName(){
            var name="Easy Code"; //first declaration
            document.writeln(name);// output Easy Code
            document.write("<br>");
            var name="Project Lord"; //Second declaration
            document.writeln(name);// output Project Lord
        }
        blogName() //Invoked function
    </script>

Problem with var

Because of hoisting and function-scoping, var can sometimes lead to confusing bugs, especially in larger programs.

Let (A Modern Replacement)

With the introduction of ES6, let was introduced to fix many of var's problems.

Characteristics of let:

  • Block-scoped: let is scoped within the nearest block {}. Displaying variable outside the block it is declared will not throw an error but the variable will not displayed.

  • Hoisted but not initialized: let is hoisted but not initialized, meaning if you try to access it before the declaration, you'll get a ReferenceError.

  • Can be updated but not re-declared: You can update the value of a let variable, but you can't declare it again in the same scope.

Example:

Block-Scoped

<script type="text/javascript">
        function  blogName(){
            if(true){
                let name="Easy Code";
                document.write(name) //Displayed inside the block
                document.write("<br>")
            }
             document.write(name) // Displayed outside the if block
        }
        blogName() //Invoked function
    </script>

Hoisted but not Initialized

<script type="text/javascript">
        function  blogName(){
            if(true){
                document.write(name) //Uncaught ReferenceError:
                // Cannot access 'name' before initialization
                let name="Easy Code";
                document.write(name) //Displayed inside the block
                document.write("<br>")
            }
        }
        blogName() //Invoked function
    </script>

Can be Updated but not re-declared ( run with out line 9 and 10)

<script type="text/javascript">
        function  blogName(){
            let name="Easy Code";//Error cannot redeclare block-scoped variable
            document.writeln(name);// output Easy Code
            name = "Easycode.com.ng"; //Updated. It willl work
            document.write("<br>");
            document.writeln(name);// output Project Lord
            document.write("<br>");
            let name="Project Lord";//Error cannot redeclare block-scoped variable
            document.writeln(name);// output Project Lord
        }
        blogName() //Invoked function
    </script>
Benefit of let: let makes your code more predictable and reduces common bugs related to scoping.

Const – For Constants

Also introduced in ES6, const is very similar to let but with an important difference: once a const variable is assigned, it cannot be reassigned.

Characteristics of const:

  • Block-scoped: Just like letconst is scoped to the nearest block {}.

  • Block-scoped: Just like let, const is scoped to the nearest block {}.

  • Must be initialized: You must assign a value when you declare a const.

  • Cannot be updated or re-declared: Once you assign a value, you cannot change it or re-declare it in the same scope.

Example:

Block-scoped

<script type="text/javascript">
    function  blogName(){
        if(true){
            const name="Easy Code";
            document.write(name) //Displayed inside the block
            document.write("<br>")
        }
         document.write(name) // Displayed outside the if block
    }
    blogName() //Invoked function
</script>

Important Note: If you declare a const object or array, the contents inside can still be modified, but you can't reassign the whole object.

Must be initialized (Remove line 3 and 4 to see correct output )

<script type="text/javascript">
        function  blogName(){
            const name="Easy Code";
            document.writeln(name);// Easy Code
            document.write("<br>");
            name="easycode.com.ng"; //Attempting to update variable
            document.writeln(name);//Uncaught TypeError:
            // Assignment to constant variable
            document.write("<br>");
        }
        blogName() //Invoked function
    </script>

Cannot be updated or re-declared

<script type="text/javascript">
    function  blogName(){
        const name="Easy Code";
        document.writeln(name);// Easy Code
        document.write("<br>");
        name="easycode.com.ng"; //Attempting to update variable
        document.writeln(name);//Uncaught TypeError:
        // Assignment to constant variable
        document.write("<br>");
        const name="Project Lord"; //Redclaring the variabl
        document.writeln(name);// Uncaught SyntaxError:
        // Identifier 'name' has already been
        document.write("<br>");
    }
    blogName() //Invoked function
</script>

Conclusion

This tutorial teach the difference between var, let and conts. The characteristic of each keyword  is  giving and the code samples are given to explain each concept. I will advice you to carefully go through each step and study them, you can drop a question or recommendation on the comment section and it will be answered as soon as possible.

Ameh Joseph Onyeke

Hello and welcome to my blog! My name is Ameh Joseph Onyeke a passionate educator and tech enthusiast with a BSc in Computer Science from Benue State University, a PGDE from the University of Maiduguri, and a Master’s in Software Engineering from Bayero University Kano. My journey blends a strong foundation in computing with a love for teaching, aiming to simplify complex tech concepts for learners at all levels. Through this blog, I provide answers and insights across 10+ programming languages to support students and tech enthusiasts in building their skills and confidence. Whether you're solving coding problems or sharpening your programming abilities, this blog is here to guide you. Let’s learn and grow together!

Post a Comment

Previous Post Next Post