var is a javascript keyword, used to declare a variable. variable declared with var has functioned
scope or global scope. Before 2015, only var is used to declare a variable, but in 2015, let and const keyword are introduced in ES6 to declare variables.
Declaring variable with var
syntax
var variable_name;
Example
<script>
var age;
</script>
Variable with name age is declared, with no value assigned. Hence a default value undefined is assigned by javascript.
Declaring variable with var with initializer(value)
<script>
var age = 20;
</script>
A variable age is declared and assigned a value 20. Here value 20 is initializer.
Declaring variable with function scope
<script>
function myage()
{
var age = 20; // function scope
document.write(age);// outputs 20
}
myage();
document.write(age); // Error
</script>
age variable is declared inside a function, Hence age is function scoped, so it can only be accessed inside function, not outside of it. If trying access outside of function, it will throw an error, as in above example.
Declaring variable with function and Global scope
<script>
var age = 30; // Global Scope
function myage()
{
var age = 20; // function scope
document.write(age); // outputs 20
}
document.write(age); // outputs 30
myage();
</script>
variable age is declared outside function and also inside function with different values. One declared outside function has global scope, and one inside function has function scope.
Variable declared with Global scope only
<script>
var age = 30; // Global scope
function myage()
{
age = 20; // Reassigned value
document.write(age);
}
document.write(age);
myage();
</script>
variable age is declared outside of function with value 30, but variable age is reassigned a new value 20 inside function myage(). Hence, the previous value 30 is overwritten with new value 20 inside function. Because of Global scope of variable age, it is accessible in the entire script or program.