var, let, const

In ECMAScript, variables are identifiers used to store data values. Variables can be declared, initialized, assigned, and modified within code. There are three ways to declare variables in ECMAScript:

  1. Declaring variables using var:
    Variables declared with the var keyword were one of the earliest methods in ECMAScript. They can be declared within a function or in the global scope. These variables can be initialized through assignment and modified in subsequent code.

    var x; // Declare a variable
    x = 5; // Assign value to variable
    
  2. Declaring variables using let:
    The let keyword is an ECMAScript 6 feature used to declare block-scoped variables. This means a variable is only accessible within the block in which it is declared and is destroyed when that block ends. The let keyword can be used in loops to avoid issues caused by variable hoisting.

    let x; // Declare a variable
    x = 5; // Assign value to variable
    
  3. Declaring variables using const:
    The const keyword is also an ECMAScript 6 feature used to declare constants. A constant must be initialized at the time of declaration and cannot be modified in subsequent code. This helps programmers avoid accidentally changing the value of a constant.

    const PI = 3.14; // Declare a constant
    

In ECMAScript, variable scope can be global or local. Global variables are accessible anywhere in the program, while local variables are only accessible within the function or code block where they are declared. ECMAScript also supports variable hoisting, meaning variables can be used before they are declared, but their value will be undefined.