Call a function: Difference between revisions

m
→‎JavaScript: Minor elaboration
m (→‎JavaScript: Minor elaboration)
Line 257:
There are no ''differences between calling subroutines and functions'' because J defines neither <code>subroutines</code> nor <code>functions</code>. Instead, J defines <code>verbs</code>, <code>adverbs</code>, and <code>conjunctions</code> which for the purpose of this task are treated as functions.
 
=={{header|JavascriptJavaScript}}==
 
The arguments to a JavaScript function are stored in a special array-like object which does not enforce arity in any way; a function declared to take ''n'' arguments may be called with none‒and vice versa‒without raising an error.
Functions can be called directly:
 
<lang javascriptJavaScript>myfunction()var foo /** Call a= function() with{ noreturn arguments*/.length };
foo() // 0
myfunction(value1,value2) /** Call a function with two arguments*/</lang>
foo(1, 2, 3) // 3</lang>
 
Neither optional (see above) nor named arguments are supported, though the latter (and the inverse of the former) may be simulated with the use of a helper object to be queried for the existence and/or values of relevant keys. <span style="color: transparent;">Seriously, what is "statement context"?</span>
Functions can also be called via an event:
 
JavaScript functions are first-class citizens; they can be stored in variables (see above) and passed as arguments.
<lang javascript><button onclick="myfunction()">Click My Button</button> /** Function is called when a click event occurs */</lang>
<lang JavaScript>var squares = [1, 2, 3].map(function (n) { return n * n }); // [1, 4, 9]</lang>
 
Naturally, they can also be returned, thus partial application is supported.
<lang JavaScript>
var make_adder = function(m) {
return function(n) { return m + n }
};
var add42 = make_adder(42);
add42(10) // 52</lang>
 
Calling a user-defined function's <tt>toString()</tt> method returns its source verbatim; that the implementation is elided for built-ins provides a mechanism for distinguishing between the two.
 
<lang JavaScript>foo.toString()
"function () { return arguments.length }"
alert.toString()
"function alert() { [native code] }"</lang>
 
Arguments are passed by value, but the members of collections are essentially passed by reference and thus propagate modification.
<lang JavaScript>var mutate = function(victim) {
victim[0] = null;
victim = 42;
};
var foo = [1, 2, 3];
mutate(foo) // foo is now [null, 2, 3], not 42</lang>
 
=={{header|Mathematica}}==