Variables in JavaScript

In programming languages variables are containers for storing data values. We can place data into these containers and then refer to the data simply by naming the variables. The variable names are also called its identifier. Variables are declared in JavaScript using var, a keyword that allocates storage space for new data and indicates to the interpreter that a new identifier is in use. The variable can be declared as follows :
  var x;
The above statement tells the interpreter that a new variable x is about to be used. The General rules for Constructing Variable name are as follows :

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names.

And also note that the JavaScript identifiers are case-sensitive. Storing a value in a variable is called variable initialization. Variables can be assigned initial values when they are declared. Example :
  var x = 2;
  var name = "John";
  var addr;
Also multiple variable can be declared with one var statement if the variables are separated by commas :
  var x=12, name = "John", addr, lastname = "wick" ;
Example :
<html>
<body>
  <p id="demo1"></p>
  <p id="demo2"></p>
  <p id="demo3"></p>
  <script>
    var x=12, name = "John", addr, lastname = "wick" ;
    document.getElementById("demo1").innerHTML = x;
    document.getElementById("demo2").innerHTML = name;
    document.getElementById("demo3").innerHTML =lastname;
  </script>
</body>
</html>
Output :

12
John
wick


JavaScript let statement :

The let statement is used to declare a variable that are scoped to the nearest enclosing block. The syntax for creating variable with let is :
  let variable_name = value;
Example :
  let x = 100, name = "jack", lastname = "riether";
<html>
<body>
  <p id="demo1"></p>
  <p id="demo2"></p>
  <p id="demo3"></p>
  <script>
    let x=12, name = "Jack", addr, lastname = "rietcher" ;
    document.getElementById("demo1").innerHTML = x;
    document.getElementById("demo2").innerHTML = name;
    document.getElementById("demo3").innerHTML =lastname;
  </script>
</body>
</html>
Output :

12
Jack
rietcher

The main difference bet var and let is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block. Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.


Next Topic :