A variable is a “container” for information you want to store. A variable’s value can change during the script. You can refer to a variable by name to see its value or to change its value.
Rules For Variable Names :
- Variable names are case sensitive.
- They must begin with a letter or the underscore (‘_’) character.
Declare Variable :
- You can create a variable with the var statement.
Syntax : var variablename = some value
- You can also create a variable without the var statement.
Variablename = some valueAssign.
- You can assign a value to a variable like this.
Var cName = "Visions" Or also like this
cName = "Visions"
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable ‘cName’ has the value “Visions”.
Lifetime of Variables
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts they are declared and end when the page is closed.
So like other programming language there are no such complexity regarding lifetime or scope of variable.
If Short if you declare variable in function then within that function used as local variable otherwise outside of function it is used by publically by all functions.
var name = "Visions Developer"
This example declares a variable, assigns a value to it, and then displays the Variable. Then the variable is displayed one more time, only this time as a heading.