JavaScript Variables

javascript-variables

Whenever we write JavaScript code, we need to store data. A JavaScript variable enables us to store data that we can easily access at different parts of the code. Also, we can view a JavaScript variable as a storage location or a container that holds particular data.

The data that a variable holds can be of different types, such as strings, numbers, and boolean.

Types of JavaScript Variable

The variables in JavaScript can be of two types, namely Local variable, and Global variable. Let’s understand each of them in detail below:

1. Local Variable

A local variable is one that you can declare within a block or function. Also, a local variable is valid within the block or function in which it is declared. You cannot access the local variable outside its block or function.

Example:

<script>
function sum () {
    var a = 5  //local variable
    var b = 5 //local variable
    var c = a + b;
}
sum();
</script>

2. Global Variable

Compared to a local variable, the scope of a global variable is much more extensive. A global variable is declared within code but outside any specific block or function. This makes it possible to use a global variable throughout a program in any function.

Example:

<script>
var a = 5; //global variable
function comparison () {
    var b = 10;
    if(a<b) {
        console.log ("a is less than b");
    }
    else {
        console.log ("b is less than 5");
    }   
}
comparison();

Rules for Declaring JavaScript Variables

While declaring variables in JavaScript, you need to keep certain rules in mind that are as follows:

  • The name of a variable must start with a letter (lowercase or uppercase) or a dollar sign ($), or an underscore (_).
  • We can use letters, numbers, underscore, and dollar signs after the first letter of the name of a variable.
  • The names of variables are case sensitive, which means that z and Z are two different variables and cannot be used interchangeably.
  • There are certain keywords in JavaScript that are reserved and thus cannot be used as the names of variables, for instance, if, else, null, void, continue, etc. are reserved words in JavaScript.

Takeaway

While coding with JavaScript, you need to make use of several variables. Also, variables are an important aspect of JavaScript as these allow you to store data or values that are essential for creating a meaningful JavaScript program.