「3.9 変数の宣言」

Variable Declaration

Before you use a variable in a JavaScript program, you should declare it. Variable are declared with the var keyword, like this:

var i;
var sum;

You can also declare multiple variables with the same var keyword:

var i, sum;

And you can combine variable declaration with variable initialization:

var message = "hello";
var i = 0, j = 0, k = 0;

If you don't specify an initial value for a variable with the var statement, the variable is declared, but its value is undefined until your code stores a value into it.

Note that the var statement can also appear as part of the for and for/in loops (introduced in Chapter 5), allowing you to succinctly declare the loop variable as part of the loop syntax itself. For example:

for(var i = 0; i < 10; i++) console.log(i);
for(var i = 0, j=10; i < 10; i++,j--) console.log(i*j);
for(var p in o) console.log(p);

C や Java のような型付きのプログラミング言語に慣れている方であれば、JavaScript の変数宣言では型が指定されていないことに気づかれたと思います。JavaScript の変数は、任意の型の値を保持できます。例えば、ある変数に数値を代入した後、同じ変数に文字列を代入してもまったく問題ありません。例を示します。

var i = 10;
i = "ten";

トラックバック - http://mnemonic.g.hatena.ne.jp/paragramma/20130228