Javascript 101: Using Variables (part 4)

Follow @tristarweb

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!

About russell

Web Developer I’m a web developer with 3 years’ experience in the media industry.My Development skills includes flash, AS3, AS2, HTML, CSS, JavaScript, Jquery, XML, PHP, and MySQL. I have a great deal of experience developing interactive user interfaces in PHP Javascript AS3 AS2I have two masters degrees in Computer Science and Multi Media and before my current role I completed a year of research at De Montfort University researching multi touch technology. during this time I developed several multi touch applications for entertainment spaces.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please wrap all source code with [code][/code] tags.

Follow Tristar on Twitter