Console Learner — An interactive JavaScript course.


3.5 Function Objects

>>>
function test(a, b, c) {
    return [a, b, c];
}


  
>>>
test.call(null, 1, 2, 3)
[1, 2, 3]
The call() method is available for all function objects and provides an alternative way to calling it. The first argument is the object context, which will be explained later.
>>>
var args = [4, 5, 6];


  
>>>
test.apply(null, args)
[4, 5, 6]
Similar to call(), the apply() method allows calling the function. Here the call arguments are provided in an array, which is more useful when the number of arguments varies or is unknown.
>>>
test.name + '/' + test.length
"test/3"
Function objects also have name and length properties, which are sometimes useful for logging and debugging.
>>>
var add = new Function('a', 'b', 'return a + b;')

  
Since functions are objects, new ones can be created using the constructor function (more later). This is seldomly used, as it is very error-prone to create code from strings.
>>>
add.name + '/' + add.length
"anonymous/2"
These functions naturally become anonymous.
>>>
add(1, 3)
4
But they behave as any other function.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.