JavaScript variables

A variable is a container used to hold data.  The container is given a name and then you can put data in and take data out when you need it.

Open jsfunction.html and save it as jsvariable.html.  Put a new blank line above the alert line.  On that line put this:

var john='Goodbye';

The line above tells the browser to create a new variable (var for short) called john.  The equals sign in programming tends to mean "make the thing on the left equal to the thing on the right".  It is known as an operator and there are others.  The browser will take the text inside the quotes and will put it into the variable (make it equal to).  The quotes are not put into the variable as they just show where the text begins and ends.

Note that there are no quotes around the variable name but there are around the text going into it.  This is a very simple concept but make sure you are clear about it as many people will get it wrong later.

Load the page in a browser and try it but it should still say hello as you have not told the browser to do anything new.  Change the alert line by deleting everything inside the brackets and replacing it with the variable name.  Remember no quotes around variable names.

Save and try and the message should have changed.

Change the new line (starting var) to put a number into the variable instead of text.  You do not need quotes around numbers so you can delete them and all the words and then put a number instead.  Save and try and the message should be just that number.

For those who have done other programming note that JavaScript can put any type of data into a variable.  For those who haven't done other programming this comment is only here because most programming languages expect you to tell them what type of data you are putting into a variable (e.g. a number or some text).  Either way you don't need to worry about it.

Variable names

There are a few guidelines when choosing variable names: