A variable’s purpose is to store information so that it can be used later. A variable is a symbolic name that represents some data that you set. To think of a variable name in real world terms, picture that the name is a grocery bag and the data it represents are the groceries. The name wraps up the data so you can move it around a lot easier, but the name is not the data!

A Variable Example

When using a variable for the first time it is not necessary to use “var” before the variable name, but it is a good programming practice to make it crystal clear when a variable is being used for the first time in the program. Here we are showing how the same variable can take on different values throughout a script.

HTML & JavaScript Code:

<html>

<body>
<script type="text/JavaScript">
<!--
var linebreak = "<br />"
var my_var = "Hello World!"

document.write(my_var)
document.write(linebreak)

my_var = "I am learning JavaScript!"
document.write(my_var)
document.write(linebreak)

my_var = "Script is Finishing up..."
document.write(my_var)
//-->
</script>
</body>

</html>

Display:

Hello World!
I am learning JavaScript!
Script is Finishing up…
We made two variables in this example–one to hold the HTML for a line break and the other for a dynamic variable that had a total of three different values throughout the script.
To assign a value to a variable, you use the equal sign (=) with the variable on the left and the value to be assigned on the right. If you swap the order, your script will not work correctly! In English, the JavaScript “myVar = ‘Hello World!’” would be: myVar equals ‘Hello World!’.
The first time we used a variable, we placed var in front to signify its first use. This is an easy way to organize the variables in your code and see when they came into existence. In subsequent assignments of the same variable, we did not need the var.

0 comments:

Post a Comment

 
Top
Blogger Template