Functions
A function is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If you exit the function without a return statement, the value undefined
is returned.
Functions are first class objects and may be assigned to other variables.
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined
(which can be implicitly cast to false). Within the function, the arguments may also be accessed through the arguments
object; this provides access to all arguments using indices (e.g. arguments, arguments, ... arguments
), including those beyond the number of named arguments. (While the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice, .sort, etc.)
All parameters are passed by value (for objects, it is the reference to the object that is passed).
var obj1 = {a : 1}; var obj2 = {b : 2}; function foo(p) { p = obj2; // Ignores actual parameter p.b = arguments; } foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter alert(obj1.a + " " + obj2.b); // writes 1 3Functions can be declared inside other functions, and access the outer function's local variables. Furthermore they implement full closures by remembering the outer function's local variables even after the outer function has exited.
var v = "Top"; var bar, baz; function foo { var v = "fud"; bar = function { alert(v) }; baz = function(x) { v = x; }; } foo; baz("Fugly"); bar; // Fugly (not fud) even though foo has exited. alert(v); // TopRead more about this topic: Java Script Syntax
Famous quotes containing the word functions:
“Adolescents, for all their self-involvement, are emerging from the self-centeredness of childhood. Their perception of other people has more depth. They are better equipped at appreciating others reasons for action, or the basis of others emotions. But this maturity functions in a piecemeal fashion. They show more understanding of their friends, but not of their teachers.”
—Terri Apter (20th century)
“Mark the babe
Not long accustomed to this breathing world;
One that hath barely learned to shape a smile,
Though yet irrational of soul, to grasp
With tiny fingerto let fall a tear;
And, as the heavy cloud of sleep dissolves,
To stretch his limbs, bemocking, as might seem,
The outward functions of intelligent man.”
—William Wordsworth (17701850)
“Those things which now most engage the attention of men, as politics and the daily routine, are, it is true, vital functions of human society, but should be unconsciously performed, like the corresponding functions of the physical body.”
—Henry David Thoreau (18171862)