JavaScript Variables

JavaScript Variables with Examples

In this article, I am going to discuss JavaScript Variables with Examples. Please read our previous article, where we discussed JavaScript Data Types in detail. At the end of this article, you will understand the following pointers in detail.

  1. What are Variables in JavaScript?
  2. Declaring and Initializing Variables in JavaScript
  3. Variable Scopes in JavaScript
  4. JavaScript Global Scope Variables
  5. Private Scope Variables in JavaScript
  6. Lexical Scoping in JavaScript
  7. What is the use of “use strict” in JavaScript?
  8. What is the difference between the let and var keywords in JavaScript?
Variables in JavaScript:

JavaScript variables are boxes for storing values. We must declare a variable in the JavaScript program before using it. A variable can be a number, a single character, string, or value indicating whether something true or false. Variable allows us to store, retrieve and change the stored information. Variable is declared with the var keyword.

Example:
<script language="javascript" type="text/javascript">
{
        var name;
        var address;
}
</script>

We can also declare multiple variables using the var keyword separated by comma (,):

<script language="javascript" type="text/javascript">
{
        var name, address;
}
</script>
JavaScript Identifier:

All JavaScript variables are identified with unique names. These unique names are called identifiers.

Variable rules:

There are some rules for declaring JavaScript variables (known as Identifier):

  1. JavaScript variables are case sensitive, for example, y and Y are different variables.
  2. Variables names must begin with a letter (a-z or A-Z) or the underscore ( _ ) character.
  3. After the first letter, we can use digits (0 to 9), for example, name1.
Variable Characteristics:

A variable has the following characteristics

  1. Name
  2. Type (the type of stored data)
  3. Value

Example: var counter=1;

In the above example, the Name of a variable is counter, a type is a number and the value is 5.

Declaring (Creating) JavaScript Variables:

We must declare a variable, before using it. Creating variables in JavaScript is referred to as “declaring” variables. We can declare a variable using the var keyword.

Example: var name;

In the above declaration, the variable is empty that is it doesn’t have any value assign yet. It means the value of a variable is undefined.

Assigning values to JavaScript Variables:

The = equal sign or assignment operator is used to assign a value to variables. Assigning a value or storing a value to a variable is called “variable initialization”. We can assign a value to the variable at the time of declaring the variable or after declaring the variable.

Example:
var name = “India”;
Or
var name;
name = “India”;

Re-declaring JavaScript Variables:

Re-declaring variables mean declaring the same variable again. If we re-declare the variable, it will not lose its actual value.

Example:
var name = “India”;
var name;

After running/execution of the program, the variable name will still have the value “India”. The value of the name is not reset or cleared when we re-declare it.

Variable Scopes in JavaScript:

The scope of a variable is nothing but the area or the region of the program in which it is defined. In JavaScript, variables have two primary scopes i.e. Private Scope and Global Scope. Let us understand the JavaScript variable scopes with some examples.

Understanding JavaScript Global Scope Variables

In the below example, we declare a variable called x outside of any JavaScript function and when you do so, it becomes a global scope variable. You can access the Global Scope variables anywhere on the page. Then we create a JavaScript function called Fun1 and within this function, we access the variable. Again, we access the variable x from outside the Fun1 function.

<html>
<head>
    <title>JavaScript Global Scope Variable Example</title>
</head>
<body>
    <script>
       var x = 10; //Global Scope
       function Fun1()
       {
          console.log("Accessing within a Function : " + x); 
       }
       Fun1();
       console.log("Accessing Globally : " + x);
    </script>
</body>
</html>

Output: When you run the above code, you will get the below output in the browser console window as expected.

JavaScript Global Scope Variables

Private Scope Variables in JavaScript:

When we declare any variable inside a function then that variable becomes private to that function only in JavaScript. If you try to access that variable from outside of that function you will get an error. Let us understand this with an example.

In the below example, we declare the variable y within the Fun1 function. This variable scope is private to the Fun1 function and can only be accessible within the Fun1 function. Then we try to access the private scope variable y from outside the function Fun1 function and it should give an error.

<html>
<head>
    <title>JavaScript Private Scope Variable Example</title>
</head>
<body>
    <script>
       var x = 10; //Global Scope
       function Fun1()
       {
          console.log("Accessing Global Variable : " + x); 
          var y = 20;
       }
       Fun1();
       console.log("Accessing Local Variable : " + y); 
    </script>
</body>
</html>

Output: When you execute the above code, you will get the following output. It is saying that y is not defined and hence we are getting Uncaught ReferenceError.

Private Scope Variables in JavaScript

Note: If you declare the variable outside the body (var x = 10), then it becomes Global and can be accessed from anywhere. On the other hand, if you declare the variable inside a function (var y = 20), then it becomes private and can only be accessible within that function. So, in other words, JavaScript follows something called Lexical Scoping. Let us understand what is Lexical Scoping in JavaScript.

Lexical Scoping in JavaScript:

In English, Lexical meaning depending on the position of something, the meaning changes. In JavaScript, here is also the same. Please have a look at the below image. When we declare the variable x outside the body, it becomes global and when we declare the variable y inside the function, it becomes local.

Lexical Scoping in JavaScript

Note: Lexical Scope means depending on the position where it is declared, its scope is defined. It does not look whether it is declared inside the function body or outside the function body. Lexical has two scopes i.e. Global and Local Scopes. Global Scope means across the whole body and local scope means inside the function.

Declaring and Initializing Variables in JavaScript:

Declaring and Initializing Variables in JavaScript are two different processes. Let us understand this with some examples.
var x = 10; //Here, we are declaring the variable as well as assigning value to it

In the below example, we have split the declaration and assigning into two steps.
var a; //Declaring the variable
a = 10; //Assigning the variable

This is very important. If you don’t understand the difference between declaring and initializing, then you will end up with a mess. Let us understand why it is important.

Please have a look at the following example. Here, within the function we simply assign the value 20 to the variable y. Please note we have not included the var keyword. But while you are running the compiler will automatically add the var keyword before the variable name.

<html>
<head>
    <title>JavaScript Auto Declaration Example</title>
</head>
<body>
    <script>
       function Fun1()
       {
          y = 20; //Declaring Auto and Assigning
          console.log("Accessing Variable y Locally: " + y); 
       }
       Fun1(); 
    </script>
</body>
</html>

Output: When you run the above application, you will get the output as expected in the browser console window as shown below.

Accessing Variable y Locally: 20

Why did I talk about the above two things (declaration and assign) separately? If you say y = 20; without using the var keyword, then it becomes global scope. That means if you don’t use the var keyword to declare a variable and if you simply assign and create a variable, then it creates a global variable. In our example, the variable y can be accessed outside the Fun1 function as shown in the below example.

<html>
<head>
    <title>JavaScript Auto Declaration Example</title>
</head>
<body>
    <script>
       function Fun1()
       {
          y = 20; //Declaring Auto and Assigning
          console.log("Accessing Variable y Locally: " + y); 
       }
       Fun1();
       console.log("Accessing Variable y Outside: " + y); 
    </script>
</body>
</html>

Output: When you run the above code, you can see the below output in the browser console.

JavaScript Variables with Examples

Actually, this is very dangerous. Think, as a programmer if you forgot to use the var keyword, then all your variables become global. So, to avoid such things, lots of JavaScript developers use something called “use strict”.

What is the use of “use strict” in JavaScript?

Using “use strict”, you are saying to the JavaScript code that you cannot create a variable without declaring it. And if you do so, you will get an error. Please have a look at the below example. This is the same example as the previous except we use “use strict”.

<html>
<head>
    <title>JavaScript Use Strict Example</title>
</head>
<body>
    <script>
       "use strict"
       function Fun1()
       {
          y = 20; //Declaring Auto and Assigning
          console.log("Accessing Variable y Locally: " + y); 
       }
       Fun1();
       console.log("Accessing Variable y Outside: " + y); 
    </script>
</body>
</html>

Output: Now, if you run the above code, you will get an error saying y is not defined as shown below and this is because now are using the “use strict” which does not allow us to create a variable without declaring it.

What is the use of “use strict” in JavaScript?

Now when you use “use strict” then you should have to use the var keyword to declare the variable as shown in the below example. Once you use the var keyword to declare the variable y, then you cannot access this variable from outside the function.

<html>
<head>
    <title>JavaScript use strict Example</title>
</head>
<body>
    <script>
       "use strict"
       function Fun1()
       {
          var y = 20; 
          console.log("Accessing Variable y Locally: " + y); 
       }
       Fun1();
    </script>
</body>
</html>

Output: Now when you run the above code, you will get the output as expected without any error.

Note: It is always a very good coding practice in JavaScript to put “use strict” at the top because by doing so, your lexical scoping is followed.

Let Keyword in JavaScript:

Like the var keyword, you can also use the let keyword in JavaScript to declare variables as shown below.

let x = 10;

What is the difference between the let and var keywords in JavaScript?

Let us understand the difference between them with an example. Please have a look at the following example. In the below example, we have not to use the var keyword to declare the variable within the Fun1 function. In this case, what JavaScript will do is, it will create the variable with the var keyword with global scope and hence you can access the variable outside the Fun1 function.

<html>
<head>
    <title>JavaScript Hoisting Example</title>
</head>
<body>
    <script>
       function Fun1()
       {
          x = 10;
       }
       Fun1();
       console.log("x="+ x);
    </script>
</body>

Let us do the same using let keyword. Let us declare the variable x within the Fun1 function using the let keyword as shown in the below example. When you use the let keyword, then in the below example, the variable x is created with local scope and hence you cannot access the variable x from outside the Fun1 function.

<html>
<head>
    <title>JavaScript Hoisting Example</title>
</head>
<body>
    <script>
       function Fun1()
       {
         let x = 10;
       }
       Fun1();
       console.log("x="+ x);
    </script>
</body>

When you run the above code, you will get the following error in the browser console window.

What is the difference between the let and var keywords in JavaScript?

In the next article, I am going to discuss JavaScript Hoisting with examples. Here, in this article, I try to explain JavaScript Variables with Examples. I hope you enjoy this JavaScript Variables with Examples article.

Leave a Reply

Your email address will not be published.