Saturday, April 30, 2011

JavaScript Variables - VIII


Like other programming languages, JavaScript variables are a container that contains a value - a value that can be changed as required.
For example, you could prompt your website users for their first name. When they enter their first name you could store it in a variable called say, firstName. Now that you have the user's first name assigned to a variable, you could do all sorts of things with it like display a personalised welcome message back to the user for example. By using a variable to store the user's first name, you can write one piece of code for all your users.

Declaring JavaScript variables

First, you need to declare your variables. You do this using the var keyword. You can declare one variable at a time or more than one. You can also assign values to the variables at the time you declare them.

Different methods of declaring JavaScript variables


// declaring one javascript variable
var firstName;

// declaring multiple javascript variables
var firstName, lastName;

// declaring and assigning one javascript variable
var firstName = 'Homer';

// declaring and assigning multiple javascript variables
var firstName = 'Homer', lastName = 'Simpson';

Using JavaScript variables

Although there are many uses for JavaScript variables, here is a quick and dirty example:

<script language="javascript" type="text/javascript" >

<!-- hide me
var firstName = prompt("What's your first name?", "");
// end hide -->

<!-- hide me
document.write(firstName);
// end hide -->

</script>
The above example opens a JavaScript prompt, prompting the user for their first name. It will then write the name to the page (in practice, you would output the name somewhere between the <body></body> tags).
I suspect you can find a much better use for your javascript variables but this simply to demonstrate how easily you can store data inside a variable - data that could change at any moment.

Rules for JavaScript Variables

  • Can contain any letter of the alphabet, digits 0-9, and the underscore character.
  • No spaces
  • No punctuation characters (eg comma, full stop, etc)
  • The first character of a variable name cannot be a digit.
  • JavaScript variables' names are case-sensitive. For example firstName and FirstName are two different variables.

No comments:

Post a Comment