Please enable Javascript to correctly display the contents on Dot Net Tricks!

Variable

Posted On : 30 Mar 2015
Updated On : 30 Mar 2015
Total Views : 2743

A JavaScript variable is just like a container to store value. The name of JavaScript variable must be as per the identifier rules.

A JavaScript identifier must start with a letter(a-z), underscore (_) or dollar sign ($) and further characters can be digits (0-9). Also, JavaScript is case-sensitive language and JavaScript keywords cannot be used as JavaScript identifier names.

Declaring JavaScript Variables

A JavaScript variable can be declared by using following two ways:

  1. With var keyword

    You can declare a JavaScript variable using var keyword. This syntax can be used to declare both local and global variables.

    <script>
    var x = 42; 
    </script>
    

    var keyword can be used to declare many variables within one statement.

    <script>
    var x=4, y=6, z=7; //one statement, many variables 
    </script>
    
  2. Without var keyword

    You can declare a JavaScript variable without var keyword. This syntax always declares a global variable and cannot be changed at the local level.

    <script>
    y = 5; //global variable
    </script>
    

Re-Declaring JavaScript Variables

JavaScript is a dynamic programming language. A JavaScript variable can be re-declared again and it will not lose its previous value. In this way, while re-declaring a JavaScript variable, if a new value is not assigned to it then it will contain previous value and if a new value is assigned to it then it will contain new value.

<script>
var x = 5;
var x; // value = 5

var y=4;
var y="Hello"; //value = "Hello"
</script>

Evaluating JavaScript Variables

A variable that is declared using the var keyword with no initial value will have the value undefined.

<script>
var x; //undefined
</script>

Also, the undefined value behaves as false when used in a boolean context.

<script>
var x; //undefined

if(!x) //returns true
{
 console.log("true");
}
else
{
 console.log("false");
}
</script>
What do you think?

I hope, now you have better understanding of javascript variable. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.