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.
A JavaScript variable can be declared by using following two ways:
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>
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>
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>
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>
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.