JavaScript Variables

In JavaScript, variables are used to store data values that can be referenced and manipulated in a program. Variables can store different types of data and are a fundamental part of writing JavaScript code.

1. Declaring Variables

JavaScript provides three ways to declare variables: var, let, and const.

1.1 var

  • The oldest way to declare variables.
  • Function-scoped or globally-scoped.
  • Can be re-declared and updated.
  • Hoisted to the top of their scope.Example:
    var x = 5;
    var x = 10; // Re-declaration allowed
    

    Try It Now

1.2 let

  • Introduced in ES6 (ES2015).
  • Block-scoped (limited to the block where it is declared).
  • Can be updated but not re-declared in the same scope.Example:
    let y = 10;
    y = 20; // Update allowed
    

    Try It Now

1.3 const

  • Introduced in ES6 (ES2015).
  • Block-scoped.
  • Cannot be updated or re-declared (used for constants).Example:
    const z = 30;
    // z = 40; // Error: Assignment to constant variable
    

    Try It Now

2. Variable Naming Rules

  • Must begin with a letter, underscore (_), or dollar sign ($).
  • Subsequent characters can include letters, numbers, underscores, and dollar signs.
  • Case-sensitive (myVariable and MyVariable are different).
  • Cannot be a reserved keyword (e.g., let, const, if).Example:
    let myVariable = 100;
    let _privateVar = "private";
    

    Try It Now

3. Variable Scope

  • Global Scope: Variables declared outside any function or block are in the global scope and accessible from anywhere.
  • Function Scope: Variables declared inside a function are local to that function.
  • Block Scope: Variables declared with let and const inside a block {} are limited to that block.Example:
    function testFunction() {
      var localVar = "I am local";
      console.log(localVar); // Accessible here
    }
    // console.log(localVar); // Error: localVar is not defined
    

    Try It Now

4. Hoisting

  • Variables declared with var are hoisted to the top of their scope but not initialized.
  • let and const are also hoisted but remain uninitialized until their declaration is encountered in the code (Temporal Dead Zone).Example:
    console.log(a); // undefined
    var a = 5;
    
    // console.log(b); // Error: Cannot access 'b' before initialization
    let b = 10;
    

    Try It Now

5. Best Practices

  • Use let and const instead of var for block-level scoping.
  • Use const when the variable should not be reassigned.
  • Use meaningful variable names for readability.
  • Initialize variables when you declare them to avoid undefined.

Summary

Variables are a fundamental part of JavaScript, allowing you to store and manipulate data. Understanding the differences between var, let, and const, along with scoping and hoisting, is essential for writing effective and error-free JavaScript code.