1. Technology

JavaScript By Example

6. Variables


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.


<title>Example 06</title>
<div id="ex"></div>
<script type="text/javascript" src="example06.js"></script>


var hello, world;
hello = 'hello';
world = "world";
document.getElementById('ex').innerHTML = hello + ' ' + world;

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. JavaScript By Example - Variables

©2014 About.com. All rights reserved.