- JavaScript Functions
- Example
- JavaScript Function Syntax
- Function Invocation
- Function Return
- Example
- Why Functions?
- The () Operator
- Example
- Example
- Example
- Note
- Functions Used as Variable Values
- Example
- Local Variables
- Example
- Function.prototype.call()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using call() to invoke a function and specifying the this value
- Using call() to invoke a function without specifying the first argument
- Transforming methods to utility functions
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- JavaScript Function call()
- All Functions are Methods
- Example
- What is this?
- Note
- See Also:
- The JavaScript call() Method
- Example
- Example
- The call() Method with Arguments
- Example
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when «something» invokes it (calls it).
Example
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, . )
The code to be executed, by the function, is placed inside curly brackets: <>
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when «something» invokes (calls) the function:
- When an event occurs (when a user clicks a button)
- When it is invoked (called) from JavaScript code
- Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will «return» to execute the code after the invoking statement.
Functions often compute a return value. The return value is «returned» back to the «caller»:
Example
Calculate the product of two numbers, and return the result:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) // Function returns the product of a and b
return a * b;
>
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different results.
The () Operator
The () operator invokes (calls) the function:
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>
Accessing a function with incorrect parameters can return an incorrect answer:
Example
function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>
Accessing a function without () returns the function and not the function result:
Example
function toCelsius(fahrenheit) <
return (5/9) * (fahrenheit-32);
>
Note
As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function result.
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:
You can use the function directly, as a variable value:
You will learn a lot more about functions later in this tutorial.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example
// code here can NOT use carName
function myFunction() let carName = «Volvo»;
// code here CAN use carName
>
// code here can NOT use carName
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Function.prototype.call()
The call() method calls the function with a given this value and arguments provided individually.
Try it
Syntax
call(thisArg) call(thisArg, arg1) call(thisArg, arg1, /* …, */ argN)
Parameters
The value to use as this when calling func . If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.
Arguments for the function.
Return value
The result of calling the function with the specified this value and arguments.
Description
Note: This function is almost identical to apply() , except that the function arguments are passed to call() individually as a list, while for apply() they are combined in one object, typically an array — for example, func.call(this, «eat», «bananas») vs. func.apply(this, [«eat», «bananas»]) .
Normally, when calling a function, the value of this inside the function is the object that the function was accessed on. With call() , you can assign an arbitrary value as this when calling an existing function, without first attaching the function to the object as a property. This allows you to use methods of one object as generic utility functions.
Warning: Do not use call() to chain constructors (for example, to implement inheritance). This invokes the constructor function as a plain function, which means new.target is undefined , and classes throw an error because they can’t be called without new . Use Reflect.construct() or extends instead.
Examples
Using call() to invoke a function and specifying the this value
In the example below, when we call greet , the value of this will be bound to object obj , even when greet is not a method of obj .
function greet() console.log(this.animal, "typically sleep between", this.sleepDuration); > const obj = animal: "cats", sleepDuration: "12 and 16 hours", >; greet.call(obj); // cats typically sleep between 12 and 16 hours
Using call() to invoke a function without specifying the first argument
If the first thisArg parameter is omitted, it defaults to undefined . In non-strict mode, the this value is then substituted with globalThis (which is akin to the global object).
.globProp = "Wisen"; function display() console.log(`globProp value is $this.globProp>`); > display.call(); // Logs "globProp value is Wisen"
In strict mode, the value of this is not substituted, so it stays as undefined .
"use strict"; globalThis.globProp = "Wisen"; function display() console.log(`globProp value is $this.globProp>`); > display.call(); // throws TypeError: Cannot read the property of 'globProp' of undefined
Transforming methods to utility functions
call() is almost equivalent to a normal function call, except that this is passed as a normal parameter instead of as the value that the function was accessed on. This is similar to how general-purpose utility functions work: instead of calling array.map(callback) , you use map(array, callback) , which avoids mutating Array.prototype , and allows you to use map with array-like objects that are not arrays (for example, arguments ).
Take Array.prototype.slice() , for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:
const slice = Array.prototype.slice; // . slice.call(arguments);
Note that you can’t save slice.call and call it as a plain function, because the call() method also reads its this value, which is the function it should call. In this case, you can use bind() to bind the value of this for call() . In the following piece of code, slice() is a bound version of Function.prototype.call() , with the this value bound to Array.prototype.slice() . This means that additional call() calls can be eliminated:
// Same as "slice" in the previous example const unboundSlice = Array.prototype.slice; const slice = Function.prototype.call.bind(unboundSlice); // . slice(arguments);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 1, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
JavaScript Function call()
With the call() method, you can write a method that can be used on different objects.
All Functions are Methods
In JavaScript all functions are object methods.
If a function is not a method of a JavaScript object, it is a function of the global object (see previous chapter).
The example below creates an object with 3 properties, firstName, lastName, fullName.
Example
const person = <
firstName:»John»,
lastName: «Doe»,
fullName: function () <
return this.firstName + » » + this.lastName;
>
>
// This will return «John Doe»:
person.fullName();
In the example above, this refers to the person object.
this.firstName means the firstName property of this.
this.firstName means the firstName property of person.
What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined . |
In an event, this refers to the element that received the event. |
Methods like call() , apply() , and bind() can refer this to any object. |
Note
See Also:
The JavaScript call() Method
The call() method is a predefined JavaScript method.
It can be used to invoke (call) a method with an owner object as an argument (parameter).
With call() , an object can use a method belonging to another object.
This example calls the fullName method of person, using it on person1:
Example
const person = <
fullName: function() <
return this.firstName + » » + this.lastName;
>
>
const person1 = <
firstName:»John»,
lastName: «Doe»
>
const person2 = <
firstName:»Mary»,
lastName: «Doe»
>
// This will return «John Doe»:
person.fullName.call(person1);
This example calls the fullName method of person, using it on person2:
Example
const person = <
fullName: function() <
return this.firstName + » » + this.lastName;
>
>
const person1 = <
firstName:»John»,
lastName: «Doe»
>
const person2 = <
firstName:»Mary»,
lastName: «Doe»
>
// This will return «Mary Doe»
person.fullName.call(person2);
The call() Method with Arguments
The call() method can accept arguments:
Example
const person = <
fullName: function(city, country) <
return this.firstName + » » + this.lastName + «,» + city + «,» + country;
>
>
const person1 = firstName:»John»,
lastName: «Doe»
>
person.fullName.call(person1, «Oslo», «Norway»);