Assigning values to variables

After you declare a variable, you can assign a value to a variable. Assigning a value to a variable means storing a value to a variable. To assign a value, use the equal sign:

var age;
age = 55;

The first line declares a variable called age. The second line stores the number 55 to our variable age. If you want, you could also combine those two lines into one, as :

age = 55;

In this one line above, we declare a variable called age when we assign the value 55. In this case, the value is declared implicitly; to explicitly declare a variable, use the command var before a variable name.

Consider the following example:

<script language="javascript">
var fName, age;
fName = "John";
age = 23;
document.write (fName);
document.write ("is");
document.write (age);
</script>

On the first line, we indicate that it is a JavaScript code. The second line declares two variables. On the third line (fName = "John";), we assign a string value to the variable fName. On the fourth line, we assign a numerical value to the variable age. As the line 5 (document.write (fName);) shows, to print a value of a variable, simply type the exact variable name with document.write () method. Line 7 prints the word "is" and line 8 prints the value, 23, of the variable age. The following shows the output of the above code.

To print "Johnis23" as "John is 23", simply add a space character around the word "is", as

<script language="javascript">
var fName, age;
fName = "John";
age = 23;
document.write (fName);
document.write (" is ");
document.write (age);
</script>

That will print:

We could simplify our code to these fewer lines:

<script language="javascript">
fName = "John";
age = 23;
document.write (fName + " is " + age);
</script>

Lines 2 and 3 each declare and assign a value. On line 4, we combine the output with the plus symbol. The output is the same as shown before: