Variables are used to store any type of JavaScript values.
To declare a variable, first write the var keyword. This tells that a variable is being created. It is then followed by the name of the variable.
var variable_name;
While declaring a variable, you can assign its value using equal (=) operator, followed by the value.
var variable_name = "value";
To declare multiple variables on a single line, write var keyword and separate each variable with a comma.
var fruit = "Apple", var2, some_number = 100;
Variable names can contain letters, digits, underscore (_) and dollar sign ($). The names must start with a letter, underscore or a dollar sign. Here are some examples:
var a = 9;
var $b = "hello";
var test$test = 50;
var _myVar = 1.2;
var employee_name1 = "john doe";
Javascript variables are case sensitive, so having variables named like var a; and var A; would be considered as being two separate variables.
var a = 9;
var A = 4;
document.write(a); //This displays 9
The above code will display the following:
9
If you declare a variable and not set its value, the variable will have value of undefined.
var name1;
document.write(name1); //This displays "undefined"
document.write("<br>");
name1 = "Homer J Simpson";
document.write(name1); //This displays "Homer J Simpson"
The above code will display the following:
undefined
Homer J Simpson
Javascript variables have two scopes: global and local.
A variable declared outside a function has global scope it's value can be accessed throughout the program.
<script type="text/javascript">
var a = 9;
function Hello() {
document.write(a); //This displays 9
}
Hello(); //Calling the Hello function
</script>
The above code will display the following:
9
A variable declared inside a function has a local scope, it would only be accessible inside the function it was declared in. The local variable will take precedence over same named global variable.
<script type="text/javascript">
var a = 9;
function Hello() {
var a = 6;
document.write(a); //This will display 6
}
Hello(); //Calling the Hello function
document.write("<br>");
document.write(a); //This will display 9
</script>
The above code will display the following:
6
9