After getting basic knowledge and some needed topics of JavaScript. Now let’s get through Variables, Operators etc.
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.
- Always remember that JavaScript is case-sensitive! A variable named "vision" is not the same as a variable named "VISION".
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.
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.
Example:
Example:
<script language=”javascript”>
var name = "Visions Developer"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>
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.
var name = "Visions Developer"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>
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.
No comments:
Post a Comment