Team LiB   Previous Section   Next Section

1.2 Variables

Variables are declared and initialized with the var statement:

var i = 1+2+3;
var x = 3, message = 'hello world';

Variable declarations in top-level JavaScript code may be omitted, but they are required to declare local variables within the body of a function.

JavaScript variables are untyped: they can contain values of any data type.

Global variables in JavaScript are implemented as properties of a special Global object. Local variables within functions are implemented as properties of the Argument object for that function. Global variables are visible throughout a JavaScript program. Variables declared within a function are only visible within that function. Unlike C, C++, and Java, JavaScript does not have block-level scope: variables declared within the curly braces of a compound statement are not restricted to that block and are visible outside of it.

    Team LiB   Previous Section   Next Section