Introduction To Javascript
Variables

Introduction

In programming, variables are used to store values which are unknown, determined by user input or circumstance and may change as the script or scripts run. If you completed the exercises in the for loop section then you have already used them. For example, if the user is prompted to enter his or her name as the page is loaded so that an appropriate greeting can be displayed, the text that they enter is stored in a variable.

Declaring Variables

You declare variables by including a statement in your script that tells the browser that the keyword that you have chosen is a variable. You can also define its value and change its value at any time in your script. You do not have to specify the type of variable (string or number etc.) when you declare the variable unlike in some programming languages.

What name should I give the variable?

As far as making the code run, the name of the variable is unimportant. There are a number of reserved words in Javascript that cannot be used as variables. As in most programming languages, these are mainly words used for Javascript statements. Javascript is CaSe SenSItiVe. You must use exactly the same combinations of upper and lower case letters when referring to the same variable. (carName and carname are different). You cannot include spaces in variables. It is usual to make compound words and capitalise the first letter of each word other than the first (eg. myCar).

Exercise 5

Add the following statement to a script to be run in the head of an HTML document changing the italicised text as appropriate.

var myName = "Write your name here"

The following statement should be added to a script in the body section of an HTML document.

document.write("Hello " + myName)

Load the page to run the script. Change the value of the variable in your code and reload the page. The message should have changed.