JavaScript By Example
Variables are the containers in which the values that your script is using are held during processing. While JavaScript doesn't require that you define variables before you use them, not defining them first may result in their not working quite the way you expect.
Best practice is to define all of the variables that need global scope in your script as a comma separated list at the top of your code as shown in this example.
Where you are using functions or objects (which we'll get to in later examples) those variables which are local to the function or object should be defined as a comma separated list at the top of the function or object.
There are rules in JavaScript as to how you can name your variables. JavaScript is case sensitive so uppercase letters are treated as different from lowercase letters and JavaScript also treats the $ and _ characters as letters when they are used in variable names. Variable names can contain both letters and numbers but must start with a letter. You can't give a variable and a function the same name but you can use the same names inside functions and objects as are used outside of those functions and objects because the scope to which the names apply is different.
Best practice is to define all of the variables that need global scope in your script as a comma separated list at the top of your code as shown in this example.
Where you are using functions or objects (which we'll get to in later examples) those variables which are local to the function or object should be defined as a comma separated list at the top of the function or object.
There are rules in JavaScript as to how you can name your variables. JavaScript is case sensitive so uppercase letters are treated as different from lowercase letters and JavaScript also treats the $ and _ characters as letters when they are used in variable names. Variable names can contain both letters and numbers but must start with a letter. You can't give a variable and a function the same name but you can use the same names inside functions and objects as are used outside of those functions and objects because the scope to which the names apply is different.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 06</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="example06.js"></script>
</body>
</html>
JavaScript
var hello, world;
hello = 'hello';
world = "world";
document.getElementById('ex').innerHTML = hello + ' ' + world;