var Statements

By: Dusty Arlia
Published on Wednesday, April 17, 2013, 09:10 PM
Last Updated on Friday, July 17, 2015 at 6:22 PM
Total Updates: 5

var statements declare one or more variables at a time. These statements create your JavaScript variable(s) to be used within your script or function.

Start off your statement with the var keyword. This var keyword declares your variable. Here is an example:

var first_name;

If there is no initializing value given with your var statement, then the variable's initial value is undefined. If you would like to set your variable to a value, do so like this:

var first_name = "Dusty";

The var keyword declares the variable, while the assignment operator (=) assigns it the string value Dusty. The expression that follows the assignment operator is optional. It is often referred to as the initializer expression. When you assign your variable a value it is called "initializing".

It's possible to declare multiple variables at once like this:

var first_name, middle_name, last_name;

It's also possible to declare and initialize these variables all at once like this:

var first_name = "Dusty", middle_name = "Armadillo", last_name = "Arlia";

Remember that the initializer expressions are optional and not required.

Variables can be declared anywhere in a script or function. When a variable is declared, no matter where in the script or function the declaration occurs, the JavaScript interpreter hoists the declaration statement to the top of the script or function. Where that variable gets initialized does not change. Wherever that initialization statement occurs is when the variable's value gets changed from undefined to the value assigned to it.

Accidentally declaring the same variable multiple times has no effect and is harmless.

Comments:

Ad: