Last time I discussed how to create your first JavaScript project – assuming you completed that tutorial, then you can read on about assigning variables withing JavaScript.
When writing your scripts in any language you will come to a time where you will want to store a value, string, object or array, temporarily to use later in your script; this is where variables come in.
A variable in JavaScript is declared firstly with the reserved word “var”. You then name the variable and finally assign it a value, as below:
var myFirstVariable = 0;
This variable has been assigned the value of zero and so if referenced in a script will act as a zero.
Example:
<script type="text/javascript"> var myFirstVariable = 0; alert (myFirstVariable+1); </script>
The Above code will return 1. At this stage there seems little point in a variable; why write “myFirstVariable” when you can just write 0. The advantage of variable is that they can be reassigned, for example:
Take a basic price calculator script in a web design project, with variables called “price1” and “price2” which are both set to zero. Then a third variable called “total”, which has a value that equals the sum of price1 + price2.
<script type="text/javascript"> var price1 = 0; var price2 = 0; var total = price1+price2; alert (myFirstVariable+1); </script>
I could then reassign the value of “price1” based upon a users input. We won’t go into the explanation of how to reassign and get a users input as this is in a later tutorial, and deserves its own explanation – but you will find an example of the script at the bottom of the post.
<script type="text/javascript"> var price1 = 0; var price2 = 0; var total = price1+price2; function setprice1 (newvalue) { price 1 = newvalue; alertPrice(); } function alertPrice() { alert (total); } </script>
What’s next?
Next time I will be talking about the fundamentals of a JavaScript function. Feel free to ask any questions beforehand!