Skip to main content

Command Palette

Search for a command to run...

var, let, and const in JavaScript

Published
6 min readView as Markdown

Introduction

Declaring variables in JavaScript using different syntaxes allows you to store and manipulate data values throughout your code. There are three primary ways to declare variables: var, let, and const. Each of these has unique features regarding scope, mutability, and behaviour.

Although you can technically declare variables without a keyword, doing so is not advisable. This approach can lead to unintended global variables and various scope issues—where the visibility and lifetime of variables can become unpredictable, making your code more difficult to debug and maintain. It is always best practice to declare variables using var, let, or const. This provides clarity about their intended use, ensuring your code is predictable, maintainable, and safer.

Let's dive deeply into var, let, and const in JavaScript

  • var

    The original way to declare variables is in JavaScript. Variables declared with var can be reassigned easily, enabling you to modify their values at any point in your code.

      // Example
      var name = "isaac";
      console.log(name); // output: isaac
      name = "Donald";
      console.log(name); // name have been reassigned, output: Donald
    

    var is also function-scoped, which means that it's accessible throughout an entire function, no matter where it's declared in the function.

      // Example
      function ageFunction() {
          console.log(myAge); // output: undefined
    
          var myAge = "I am 10 years old!"; // This variable is function-scoped
    
          console.log(myAge); // output: "I am 10 years old!"
      }
    
      ageFunction();
    
      console.log(myAge); // This will throw a ReferenceError: myAge is not defined
    

    In the ageFunction, the variable myAge is declared using var, which causes its declaration to be hoisted to the top of the function scope. This leads to the first console.log(myAge); outputting undefined instead of "I am 10 years old!" since the initialization hasn't happened yet. After the line var greeting = "I am 10 years old!", the second console.log(myAge); correctly logs "I am 10 years old!" because the variable is now initialized. However, if you try to log myAge outside of the function, you'll encounter a ReferenceError, as it isn't accessible in the global scope and is only defined within the function.

      // Example
      {
          var greeting = "Hello, World!"; // Declare a variable using var inside a block
          console.log(greeting); // Output: Hello, World!
      }
    
      console.log(greeting); // Output: Hello, World! (still accessible outside the block)
    

    Using var within a block scope can result in unexpected behaviour since var is not limited to block scope; it is either function-scoped or globally scoped if declared outside of a function. Consequently, if you declare a variable with var inside a block, it will remain accessible even outside that block.

  • let

    Introduced in ES6 (also known as ECMAScript 2015), the let keyword allows for block-scoped variables, meaning they are confined to the block { } where they are declared. This feature makes let a safer and more predictable choice, particularly in complex code, as it minimizes the risk of unintentional variable conflicts or scope problems. Additionally, let is versatile and can be reassigned as needed, allowing for more flexible variable management within a block.

      // Example
      let weekDay = "monday"
      console.log(weekDay) // output: monday
      weekDay = "friday"
      console.log(weekDay) // weekDay reassigned, output: friday
    
      // Example
      {
          let weekend = "weekend is a good time to rest.";
          console.log(weekend); // Output: weekend is a good time to rest.
      }
    
      // Trying to access 'message' outside the block
      console.log(weekend); // This will throw a ReferenceError
    

    The variable weekend is declared inside a block, making it accessible only within that block. JavaScript doesn’t recognized weekend in this context because it only exists within the { ... } where it was defined. This leads to a ReferenceError, which is JavaScript's way of signaling that it can't locate the variable in the current context.

      // Example
      function calculateArea(length, width) {
          let area = length * width; // Declare a variable 'area' using let
          console.log("Original Area:", area); // Output the original area
    
          // Reassigning the area to a new value (e.g., adding a fixed value)
          area += 10; // Add 10 to the original area
          console.log("New Area after reassignment:", area); // Output the new area
    
          return area; // Return the modified area
      }
    
      // Example usage
      console.log(calculateArea(10, 10)); // Output: Original Area: 100, New Area after reassignment: 110
      console.log(calculateArea(7, 3));   // Output: Original Area: 21, New Area after reassignment: 31
    

    In the calculateArea function, the area is initially determined by multiplying the length and width, and this value is displayed as the "Original Area." Then, the area is increased by 10, resulting in a "New Area after reassignment," which is also shown. Ultimately, the updated area value is returned, providing the result after the addition in each example calculation.

  • const

    Introduced in ES6, const behaves similarly to let regarding block scope but is specifically used for constants. Once a variable is declared with const and assigned an initial value, it cannot be reassigned.

      // Example
      const birthYear = 2014
      console.log(birthYear) // output: 2014
      birthYear = 2010
      console.log(birthYear) //Uncaught TypeError: Assignment to constant variable
    
      // Example
      {
          const message = "I am inside a block."; // Declare a constant inside the block
          console.log(message); // Output: I am inside a block.
      }
    
      // Trying to access the constant outside the block
      console.log(message); // This will throw a ReferenceError
    

    The constant message is declared within a block, making it block-scoped and only accessible inside that block. If you try to access message from outside the block, it will result in a ReferenceError since it's outside its defined context.

      // Example
      function calculateArea(radius) {
          const pi = 3.14; // Declare a constant for π
    
          // Calculate area using the constant
          const area = pi * radius * radius;
          return area; // Return the calculated area
      }
    
      console.log(calculateArea(5)); // Output: 78.5
      console.log(calculateArea(10)); // Output: 314
    

    In the calculateArea function, a constant named pi is defined as 3.14 to represent π. This value is then utilized to compute the area of a circle using the formula pi * radius * radius, and the function returns this calculated result. For instance, when you call calculateArea(5), it returns 78.5, and calculateArea(10) returns 314, based on the radius given.

    However, if the const variable refers to an object or an array, you can still change the contents of that object or array; only the reference to the variable itself remains unchanged

      // Example on array
      const numbers = [1, 2, 3];
      console.log('Original numbers:', numbers); // Output: Original numbers: [1, 2, 3]
    
      // Modifying an element in the array
      numbers[0] = 10; // This changes the first element from 1 to 10
      console.log('Modified numbers:', numbers); // Output: Modified numbers: [10, 2, 3]
    
      // Example on object
      const car = { brand: "Toyota", model: "Camry" };
      console.log("Original car:", car); // Output: Original car: { brand: 'Toyota', model: 'Camry' }
    
      // Changing a property of the object
      car.model = "Corolla"; // This is allowed because we're modifying the content of the object, not the reference
      console.log("Updated car:", car); // Output: Updated car: { brand: 'Toyota', model: 'Corolla' }
    
  • Conclusion

    In JavaScript, the most common variable declarations are made using var, let, and const, with differences in scoping and reusability. While var is either function-scoped or globally scoped and can be redeclared or reinitialized, let and const cannot be redeclared, although let can be reinitialized. In current JavaScript coding, it is recommended to employ let and const statements to avoid issues related to block scope variables and reassignment.

    Thank you!