Variables in JavaScript

SEARCH THIS SITE

Custom Search

Variables in javascript are discussed with examples and explanations.

Variables in Javascript

Variables are used in javascript to store data of many types. A variable is declared using the keyword var followed by the name of the variable. In the example below, x is defined as a variable and assigned the value 5. y is defined as a variable then assigned the value x + 7. Run the sample program below and check that the answer displayed is 12.

<!DOCTYPE html>
<html>
<body>
<script>
var x = 5;
var y;
y = x+7;
alert(y);
</script>
</body>
</html>

Several Variables in one Statement

One statement can be used to define several variables. In the sample program below 3 variables howManyKilos = 12 , pricePerKilo = 5 , y are defined using one statement only. Run the sample program and check that 60 is displayed. (Note that the operator * is the multiplication)

<!DOCTYPE html>
<html>
<body>
<script>
var howManyKilos = 12 , pricePerKilo = 5 , y;
y = howManyKilos*pricePerKilo;
alert(y);
</script>
</body>
</html>

Undefined Value of a Variable

A variable whose value is undefined will give an erroneous result if used in calculations. In the sample program below the variable howManyKilos is defined but its value is undefined. Run the sample program and check that NaN is displayed. NaN means not a number and this is due to the fact that variable howManyKilos has no value.

<!DOCTYPE html>
<html>
<body>
<script>
var howManyKilos , pricePerKilo = 5 , y;
y = howManyKilos*pricePerKilo;
alert(y);
</script>
</body>
</html>


Books and References

1 - A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half - Mark Myers
2 - JavaScript and JQuery: Interactive Front-End Web Development 1st Edition - Jon Duckett - ISBN-13: 978-1118531648
3 - A Smarter Way to Learn HTML & CSS: Learn it faster. Remember it longer. (Volume 2) - Mark Myers
4 - http://www.w3schools.com/js/default.asp - JavaScript Tutorial