JavaScript function calls involve invoking a function to execute its code. You can call a function by using its name followed by parentheses ()
, optionally passing arguments inside the parentheses.
Syntax:
call()
Return Value: It calls and returns a method with the owner object being the argument.
JavaScript Function Call Examples
Example 1: This example demonstrates the use of the call() method.
// function that returns product of two numbers function product(a, b) {
return a * b;
} // Calling product() function let result = product.call( this , 20, 5);
console.log(result); |
100
Explanation: This JavaScript code defines a `product()` function that returns the product of two numbers. It then calls `product()` using `call()` with `this` as the context (which is typically the global object), passing 20 and 5 as arguments. It logs the result, which is 100.
Example 2: This example display the use of function calls with arguments.
let employee = { details: function (designation, experience) {
return this .name
+ " "
+ this .id
+ designation
+ experience;
}
} // Objects declaration let emp1 = { name: "A" ,
id: "123" ,
} let emp2 = { name: "B" ,
id: "456" ,
} let x = employee.details.call(emp2, " Manager " , "4 years" );
console.log(x); |
B 456 Manager 4 years
Explanation:
- JavaScript defines object employee with details() method. emp1 and emp2 created. call() modifies emp2, logs result.
-
Objects
emp1
andemp2
created.call()
modifiesemp2
, logging concatenated details with updated properties in JavaScript code.
We have a complete list of Javascript Functions, to check those please go through the Javascript Function Complete reference article.
Supported browsers