What is JavaScript Variable

In this article, we are reading about “What is JavaScript Variable“.
JavaScript variable is simply a name of the storage location. There are two types of variables in JavaScript: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
  1. The name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  2. After the first letter, we can use digits (0 to 9), for example, value1.
  3. JavaScript variables are case sensitive, for example x and X are different variables.

A real-life analogy

We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely-named sticker on it.
For instance, the variable message can be imagined as a box labeled “message” with the value “Hello!” in it:
What is JavaScript Variable
We can put any value into the box.
Also, we can change it. The value can be changed as many times as needed:
1
2
3
4
let message;
message = 'Hello!';
message = 'World!'; // value changed
alert(message);
When the value is changed, the old data is removed from the variable:
What is JavaScript Variable
We can also declare two variables and copy data from one into the other.
1
2
3
4
5
6
7
8
9
let hello = 'Hello world!';
let message;

// copy 'Hello world' from hello into message
message = hello;

// now two variables hold the same data
alert(hello); // Hello world!
alert(message); // Hello world!

Correct JavaScript variables

1
2
var x = 10;
var _value="sonoo";

Incorrect JavaScript variables

1
2
var 123=30;
var *aa=320;

Example of JavaScript variable

Let’s see a simple example of JavaScript variable.
1
2
3
4
5
6
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Output
1
30

JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:
1
2
3
4
5
6
7
8
9
10
11
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>

JavaScript global variable

JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable. For example:
1
2
3
4
5
6
7
8
9
10
11
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Output
1
200 200
So in this article, we read about “What is JavaScript Variable“.

Comments