β 1. What Is a Function Call?
A function call executes the code inside a function definition.
jsCopyEditfunction greet() {
console.log("Hello!");
}
greet(); // π This is a function call
π 2. Calling a Function with Arguments
Functions can accept parameters when called:
jsCopyEditfunction add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
a
andb
are parameters2
and3
are arguments
π 3. Calling a Function Stored in a Variable
jsCopyEditconst sayHi = function() {
console.log("Hi!");
};
sayHi(); // Function call
π 4. Calling Arrow Functions
jsCopyEditconst double = x => x * 2;
console.log(double(5)); // 10
π 5. Function Call Inside Another Function
jsCopyEditfunction multiply(x, y) {
return x * y;
}
function square(n) {
return multiply(n, n);
}
console.log(square(4)); // 16
π 6. Method Call (Function inside an Object)
jsCopyEditconst person = {
name: "Alice",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // "Hello, my name is Alice"
π 7. Function Call with call()
and apply()
Used to control the this
value during a call.
jsCopyEditfunction showName() {
console.log(this.name);
}
const user = { name: "Bob" };
showName.call(user); // "Bob"
showName.apply(user); // "Bob"
call(arg1, arg2, ...)
passes arguments individuallyapply(arg1, [arg2, arg3])
passes arguments as an array
π 8. Function Call with bind()
Returns a new function with this
fixed.
jsCopyEditconst user = { name: "Dana" };
function introduce() {
console.log("I am " + this.name);
}
const boundIntro = introduce.bind(user);
boundIntro(); // I am Dana
π 9. Self-Invoking Function (IIFE)
jsCopyEdit(function() {
console.log("Runs immediately!");
})();
π 10. Callback Function Calls
Passing a function as a value to another function.
jsCopyEditfunction process(callback) {
callback();
}
process(function() {
console.log("Callback was called!");
});
π§ͺ Practice Tasks
- Create a function
welcome(name)
that returns"Welcome, <name>"
. - Create an object
car
with a methodstart()
that prints"Engine started"
. - Use
call()
to call a function with a custom object asthis
.
π§ Quick Recap Table
Call Type | Example | this Value |
---|---|---|
Regular call | myFunc() | undefined or window |
Method call | obj.method() | obj |
call() | func.call(obj) | obj |
apply() | func.apply(obj) | obj |
bind() | func.bind(obj) | Returns new function with bound this |
IIFE | (function() {})() | Immediate execution |
Would you like this tutorial in:
- π PDF format for printing/studying?
- π» Live example playground (CodePen, JSFiddle)?
- π§ Practice quiz?