Javascript Variable: Declare, Assign a Value with Example

[vc_row][vc_column][vc_column_text]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:

var name;

Assign a Value to the Variable

You can assign a value to the variable either while declaring the variable or after declaring the variable.

var name = "John";

OR

var name;

name = "John";

Naming Variables

Though you can name the variables as you like, it is a good programming practice to give descriptive and meaningful names to the variables. Moreover, variable names should start with a letter and they are case sensitive. Hence the variables student name and studentName are different because the letter n in a name is different (n and N).

Try this yourself:

This code is editable. Click Run to Execute

1
<html>
2
<head>
3
<title>Variables!!!</title>
4
<script type="text/javascript">
5
var one = 22;
6
var two = 3;
7
var add = one + two;
8
var minus = one - two;
9
var multiply = one * two;
10
var divide = one/two;
11
    document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
12
    document.write(one + " + " + two + " = " + add + "<br/>");
13
    document.write(one + " - " + two + " = " + minus + "<br/>");
14
    document.write(one + " * " + two + " = " + multiply + "<br/>");
15
    document.write(one + " / " + two + " = " + divide + "<br/>");
16
</script>
17
</head>
18
<body>
19
</body>
20
</html>

[/vc_column_text][/vc_column][/vc_row]