Referencia de JavaScript 1.5:Sentencias:var
De MDC
Tabla de contenidos |
[editar] Summary
Declares a variable, optionally initializing it to a value.
| Statement | |
| Implemented in: | JavaScript 1.0, NES 2.0 |
| ECMA Version: | ECMA-262 |
[editar] Syntax
var varname1 [= value1], varname2 [= value2], ..., varnameN [= valueN];
[editar] Parameters
-
varnameN - Variable name. It can be any legal identifier.
-
valueN - Initial value of the variable. It can be any legal expression.
[editar] Description
The scope of a variable is the current function or, for variables declared outside a function, the current application.
Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable. However, it is recommended to always use var, and it is necessary within functions in the following situations:
- If a variable in a scope containing the function (including the global scope) has the same name.
- If recursive or multiple functions use variables with the same name and intend those variables to be local.
Failure to declare the variable in these cases will very likely lead to unexpected results.
[editar] Examples
[editar] Example: Using var
The following example declares two variables, num_hits and cust_no, and initializes both to the value 0.
var num_hits = 0, cust_no = 0;