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:
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.
There are a few guidelines when choosing variable names:
- avoid spaces and other special characters (- and _ are safe but not really needed if you follow the other guidelines)
- use names which describe what will be in the variable (so myMessage would be a better name than john for this example)
- if a variable name is made up of more than one word use camel case where each new "word" starts with a capital (as in myMessage)