In JavaScript, variables are used to store data values. You can declare variables using the var, let, or const keywords. Each of these keywords has different characteristics and scoping rules.

Declaring Variables

  1. Using var

    The var keyword is function-scoped and can be re-declared and updated within its scope. However, var has some issues with block scoping, which is why let and const were introduced in ES6.

      var x = 5;
    var y = 10;
    var z = x + y;
    console.log(z); // Outputs: 15
      
  2. Using let

    The let keyword is block-scoped, meaning it is only accessible within the block where it is declared. It can be updated but not re-declared within the same scope.

      let a = 5;
    let b = 10;
    let c = a + b;
    console.log(c); // Outputs: 15
      
  3. Using const

    The const keyword is also block-scoped, but it cannot be updated or re-declared within the same scope. Variables declared with const must be initialized at the time of declaration.

      const p = 5;
    const q = 10;
    const r = p + q;
    console.log(r); // Outputs: 15
      

Variable Scope

  1. Global Scope

    Variables declared outside any function or block have a global scope and can be accessed from anywhere in the code.

      var globalVar = "I am global";
    
    function showGlobalVar() {
        console.log(globalVar); // Outputs: "I am global"
    }
    
    showGlobalVar();
      
  2. Function Scope

    Variables declared inside a function are function-scoped and cannot be accessed outside the function.

      function myFunction() {
        var localVar = "I am local";
        console.log(localVar); // Outputs: "I am local"
    }
    
    myFunction();
    // console.log(localVar); // Error: localVar is not defined
      
  3. Block Scope

    Variables declared with let and const inside a block (e.g., within {}) are block-scoped and cannot be accessed outside the block.

      {
        let blockScopedVar = "I am block scoped";
        console.log(blockScopedVar); // Outputs: "I am block scoped"
    }
    // console.log(blockScopedVar); // Error: blockScopedVar is not defined
      

Example in HTML with JavaScript

Here’s an example demonstrating the use of var, let, and const in JavaScript within an HTML file:

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Variables Example</title>
</head>
<body>
    <h1>JavaScript Variables Example</h1>
    <p id="result"></p>

    <script type="text/javascript">
        // Using var
        var x = 5;
        var y = 10;
        var z = x + y;

        // Using let
        let a = 5;
        let b = 10;
        let c = a + b;

        // Using const
        const p = 5;
        const q = 10;
        const r = p + q;

        // Variable scope
        function showLocalScope() {
            var localVar = "I am local";
            return localVar;
        }

        // Block scope
        let blockScopedVar;
        {
            let tempVar = "I am block scoped";
            blockScopedVar = tempVar;
        }

        document.getElementById('result').textContent = `
            Using var: ${z}\n
            Using let: ${c}\n
            Using const: ${r}\n
            Local scope: ${showLocalScope()}\n
            Block scope: ${blockScopedVar}
        `;
    </script>
</body>
</html>
  

Undefined

In JavaScript, when you declare a variable but do not assign a value to it, the variable is automatically assigned the special value undefined. This means that the variable exists but has not been given a meaningful value yet.

Example of Undefined Variables

Here’s a brief example to illustrate this concept:

  // Declare a variable without assigning a value
let myVariable;

// Check the value of the variable
console.log(myVariable); // Outputs: undefined
  

Explanation

  1. Declaration: When you declare a variable using let, var, or const without initializing it, JavaScript sets its value to undefined.

      let myVariable; // Variable declared but not initialized
      
  2. Default Value: The default value for uninitialized variables is undefined. This indicates that the variable has been declared but has not yet been given a specific value.

      console.log(myVariable); // Outputs: undefined
      
  3. Undefined Type: undefined is a type itself in JavaScript, and it represents a variable that has been declared but not yet assigned a value.

Example with var, let, and const

  // Using var
var a;
console.log(a); // Outputs: undefined

// Using let
let b;
console.log(b); // Outputs: undefined

// Using const
const c; // This will cause an error because const variables must be initialized at the time of declaration
  

Variable Hoisting in JavaScript

Variable hoisting is a behavior in JavaScript where variable declarations are moved, or “hoisted,” to the top of their containing scope during the compilation phase before the code is executed. This means that you can use variables in your code before they are declared.

How Hoisting Works

  1. Declarations Are Hoisted: Only the declarations are hoisted, not the initializations. If a variable is declared and initialized after it is used, the declaration is hoisted, but the initialization remains in place.
  2. Function Declarations Are Hoisted: Entire function declarations (both the name and the body) are hoisted to the top of their containing scope.

Examples of Variable Hoisting

Example 1: Variable Declarations

Consider the following code:

  console.log(myVar); // Output: undefined
var myVar = 5;
console.log(myVar); // Output: 5
  

This code behaves as if it were written like this:

  var myVar;
console.log(myVar); // Output: undefined
myVar = 5;
console.log(myVar); // Output: 5
  

The declaration var myVar is hoisted to the top of the scope, but the initialization myVar = 5 stays in place.

Example 2: Function Declarations

Consider the following code:

  myFunction(); // Output: "Hello, world!"

function myFunction() {
    console.log("Hello, world!");
}
  

This code behaves as if it were written like this:

  function myFunction() {
    console.log("Hello, world!");
}

myFunction(); // Output: "Hello, world!"
  

The entire function declaration is hoisted to the top of the scope.

Hoisting with let and const

Variables declared with let and const are also hoisted, but they are not initialized with undefined. Instead, they are in a “temporal dead zone” (TDZ) from the start of the block until the declaration is encountered. Accessing the variable before the declaration results in a ReferenceError.

Example with let and const

  console.log(myLetVar); // ReferenceError: Cannot access 'myLetVar' before initialization
let myLetVar = 5;

console.log(myConstVar); // ReferenceError: Cannot access 'myConstVar' before initialization
const myConstVar = 10;
  

Best Practices

  • Declare Variables at the Top: To avoid confusion and bugs, it is a good practice to declare all variables at the top of their scope (function or block).
  • Use let and const: Prefer let and const over var to avoid issues related to hoisting and to benefit from block scoping and the TDZ.