JavaScript Variables
A variable is used to store the data. It stores only one
value.
Rules for the variable:
·
Variable names must begin with a letter
·
Variable names can also begin with $ and _ (but
we will not use it)
·
Variable names are case sensitive (y and Y are
different variables)
·
Both JavaScript statements and JavaScript
variables are case-sensitive.
syntax:
var identifier;
Ex1:
<!DOCTYPE html>
<html>
<body>
<script>
var x=5;
var y=6;
var z=x+y;
document.write(x + "<br>");
document.write(y + "<br>");
document.write(z + "<br>");
</script>
</body>
</html>
Ex2: using Arithmetic operators
<!DOCTYPE html>
<html>
<body>
<p>Given that
y=5, calculate x=y+2, and display the result.</p>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function myFunction()
{
var y=5;
var x=y+2;
var
demoP=document.getElementById("demo")
demoP.innerHTML="x="
+ x;
}
</script>
</body>
</html>
Ex3:
<!DOCTYPE html>
<html>
<body>
<script>
var person=new
Object();
person.firstname="Rajendra";
person.lastname="prasad";
person.age=50;
person.eyecolor="blue";
document.write(person.firstname
+ " is " + person.age + " years old.");
</script>
</body>
</html>
Example program
<html>
<head>
<script
language="JavaScript">
var name=prompt("enter ur name",
"Name");
</script>
</head>
<body>
<script
language="JavaScript">
document.write("<h2>Hello
"+name+"</h2>");
</script>
</body>
</html>
Type any name in that field and
click on ok button
No comments:
Post a Comment