Variables in JavaScript
This program from the
input
page of these notes:
<html>
<!-- Getting input from the user -->
<head>
<title>My second program</title>
</head>
<body>
<script>
userName = prompt("What is your name", "")
alert("Hello " + userName + ".")
</script>
This text will appear after you close the alert.
</body>
</html>
used a variable to store the name that was entered by the user.
Variables
JavaScript uses variables as temporary storage whilst the program is running so this
little program is asking the user for a name, storing the user's input into the variable
named userName and then displaying this value in the alert.
If you already know JavaScript you may notice that I've not declared the variable.
This is sloppy practice and bad things happen on larger projects if you don't declare
variables. At the moment we're still chugging round the car park in first gear.
Note that the name of the variable starts with a small letter and has a capital letter
in the middle. This is just the way things are done in JavaScript. More about that on the
JavaScript names
page.
Case Sensitive
Don't forget that variable names are case sensitive. If you had typed:
userName = prompt("What is your name", "")
alert("Hello " + UserName + ".")
then the welcome message would not have appeared and the Error Console would
have told you "UserName is not defined".
|