Javascript: the Beginning - Variables
(Page 4 of 4 )
Variables, simply put, are containers that had data. The name variable means that the data inside can change; it varies. Some of the higher level programming languages are picky about what type of data you place in them. Not JavaScript. It, like many nerds, is desperate and will take whatever it can get.
There are, however, rules for naming a variable. For starters, they are case-sensitive, meaning that you can have a variable named my_variable and a variable named MY_VARIABLE and JavaScript will see it as two different variables. They must also begin with a letter or an underscore.
This is how you declare or assign a value to a variable:
<html>
<head>
</head>
<body>
<script type="text/Javascript">
var my_variable = "James Payne"
document.write(my_variable + "<BR>")
document.write("<i>"+my_variable+"</i>")
</script>
</body>
</html>
The above code would print out:
James Payne
James Payne
The part var my_variable = "James Payne" names the variable and assigns it the value of James Payne. We then write the value of my_variable to the screen twice, inserting a page break in between and italicizing the second printing.
You can opt not to use the var in front of the variable name if you wish, though leaving it in makes it easier to identify if you ever need to go back to the code.
Scope of a Variable
While we will cover this more in depth later on, variables have two types of life spans. If you declare the variable inside of a function (more on this later), it disappears once the function is completed. If you declare it outside of a function, it disappears when the page is closed (don't worry; if a user revisits the page, the process starts all over again).
Well that's it for this article. In our next tutorial, we will cover how to insert special characters, working with statements, and if we have time, working with operators. Till then...
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |