JavaScript Variable: Declare, Assign a Value Part 2

javascript

Variables are used to store values (name = “John”) or expressions (sum = x + y).

Declare Variables in JavaScript

Before using a variable, you first need to declare it. You have to use the keyword var to declare a variable like this

JavaScript Variable  Declare Assign a Value

 

var name;

Assign a Value to the Variable

You can assign a value to a variable when declaring a variable or after declaring a variable

 

var name = "John";


OR

 

var name;

name = "John";


Naming Variables

Although you can name the variables as you wish, it is a good programming practice to name the variables descriptively and meaningfully. In addition, variable names must begin with a letter and are sensitive. Therefore the variable student name and student name are different because the letter n in the name is different (n and N).

Try this yourself:

 

<html>
<head>
<title>Variables!!!</title>
<script type=”text/javascript”>
var one = 22;
var two = 3;
var add = one + two;
var minus = one – two;
var multiply = one * two;
var divide = one/two;
document.write(“First No: = ” + one + “<br />Second No: = ” + two + ” <br />”);
document.write(one + ” + ” + two + ” = ” + add + “<br/>”);
document.write(one + ” – ” + two + ” = ” + minus + “<br/>”);
document.write(one + ” * ” + two + ” = ” + multiply + “<br/>”);
document.write(one + ” / ” + two + ” = ” + divide + “<br/>”);
</script>
</head>
<body>
</body>
</html>

JavaScript Variable  Declare Assign a Value