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:
varname_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:
vari;// One simple variablevarj=0;// One var, one valuevarp,q;// Two variablesvargreeting="hello"+name;// A complex initializervarx=2.34,y=Math.cos(0.75),r,theta;// Many variablesvarx=2,y=x*x;// Second var uses the firstvarx=2,// Multiple variables...f=function(x){returnx*x},// each on its own liney=f(x);
If a var statement appears
within the body of a function, it defines local variables, scoped to
that function. When var ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access