Declaration Statements

The var and function are declaration statements—they declare or define variables and functions. These statements define identifiers (variable and function names) that can be used elsewhere in your program and assign values to those identifiers. Declaration statements don’t do much themselves, but by creating variables and functions they, in an important sense, define the meaning of the other statements in your program.

The subsections that follow explain the var statement and the function statement, but do not cover variables and functions comprehensively. See Variable Declaration and Variable Scope for more on variables. And see Chapter 8 for complete details on functions.

var

The var statement declares a variable or variables. Here’s the syntax:

var name_1 [ = value_1] [ ,..., name_n [= value_n]]

The var keyword is followed by a comma-separated list of variables to declare; each variable in the list may optionally have an initializer expression that specifies its initial value. For example:

var i;                                        // One simple variable
var j = 0;                                    // One var, one value
var p, q;                                     // Two variables
var greeting = "hello" + name;                // A complex initializer
var x = 2.34, y = Math.cos(0.75), r, theta;   // Many variables
var x = 2, y = x*x;                           // Second var uses the first
var x = 2,                                    // Multiple variables...
    f = function(x) { return x*x },           // each on its own line
    y = f(x);

If a var statement appears within the body of a function, it defines local variables, scoped to that function. When var ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.