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.
Table of Contents
ToggleAMPThe variables in JavaScript can be of two types, namely Local variable, and Global variable. Let’s understand each of them in detail below:
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>
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();
While declaring variables in JavaScript, you need to keep certain rules in mind that are as follows:
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.
Hi! I am Pankaj, a full-time content specialist and a part-time programmer and marketer. I love to explore new places and also new ideas. I am an inquisitive person with a passion to learn new skills through every possible opportunity that comes in the way.