compuhelpindia.com

JavaScript Variable

Compuhelpindia.com
« Previous                                                                                                                                       Next Chapter »


JavaScript variables are "containers" for storing information:
Examples in each Chapter
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var x=7;
var y=9;
var z=x+y;
document.write(x + "<br>");
document.write(y + "<br>");
document.write(z + "<br>");
</script>
</body>
</html >

Output:




Declaring JavaScript Variables.
Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
Example:
var num; 

After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign: Example:
num="10"; 
In the example below we create a variable called num, assigns the value "num" to it, and put the value inside the HTML paragraph with id="demo":
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click button to create a variable</p>
<button onclick="Show()">Check Here</button>
<p id="demo"></p>
<script>
function Show()
{
var num="10";
document.getElementById("demo").innerHTML=num;
}
</script>
</body>
</html> 

Output:

Click button to create a variable