Let’s say we want to keep track of someone’s name while they are visiting a particular webpage, we could collect their first name using something like the
To store something like a name, we’d use code like this:
var myName = "Trevor Page";
- The name of the variable (mandatory)
- A value for the declared variable (optional)
In the example above, we’ve used the keyword
myName as the variable’s name. If you’ve ever used a programming language before, you should be completely comfortable with this. If this is your first time, then keep reading. Finally, and optionally, we’ve assigned a value to our variable:
"Trevor Page" is the String we’ve assigned.
Now if we were to type in the variable name
myName somewhere below the example code above, then we can retrieve the value that’s been stored in our variable.
To display what we have stored in our variable, we could use the
alert function to display a popup alert on the screen showing the contents of the
Here’s what that code would look like:
All this code will do is display an alert box which will contain the contents of the
Let’s actually SEE this code in action shall we? Go ahead and click the button below and then type in your name:
Note: Feel free to click on this button multiple times and enter different names every time, you’ll see that the values you enter each time are stored into the
myName and will override the previous value.
This is a time saving process that will free up your precious brainpower to focus on more important things, like what to eat for dinner!
If this is your first time learning about variables, I’d also suggest you read another article where I go in depth on how variables work (as they pertain to the Java language), just click here to read more about variables.
And as always, don’t forget to fill out the form below and receive a free goodie delivered directly to your inbox. More detail on the free swag below!