How to use variables in scripts

If you just declare variables then they are not very useful. Somehow you have to use these variables to make them useful. To use a variable in JavaScript you have to make a call to it after it has been declared.

var DanBike = "Honda PCX";
document.write(DanBike);

The first line declares a variable with a string value and the second line is the document.write() command that writes the value of the variable DanBike to the browser.

Let’s say that you want to add two text strings, a text string and the value of the variable DanBike, then the text string needs quotation marks around it and the operator + needs to be placed between the two text strings. Notice the space before the second quotation mark!

var DanBike = "Honda PCX";
document.write("Dan has a " + DanBike);

You can also add the value of a variable in the middle of a string.

var DanBike = "Honda PCX";
document.write("The "  +DanBike + " is awesome.");

Note:
Be careful not to place the variable name withing quotation marks otherwise the browser will see it as part of the string and it will be printed as it is (instead of its value).

You can even create a variable for each piece of string you want to add then add the values of the variables.

var DanBike = "Honda PCX";
var FirstText = "The ";
var LastText= " is awesome.";
document.write(FirstText + DanBike + LastText);

Using this method gives you the possibility to change the value of a variable in order to get a different output without the need to modify the document.write() command.

Note:
You can place HTML tags within the values of your variables.

var DanBike = "Honda PCX";
var FirstText = "The ";
var LastText = " is awesome.";
document.write(FirstText + DanBike + LastText);

Leave a Reply