πŸ“˜ JavaScript Function Invocation

βœ… 1. What Is Function Invocation?

Function invocation means executing a function β€” making it run.

jsCopyEditfunction greet() {
  console.log("Hello!");
}

greet(); // πŸ”” Function is invoked here

πŸ“Œ 2. Types of Function Invocation

JavaScript provides several ways to invoke functions, each with different this behavior.


A. Simple Invocation

Most common: call a function by its name followed by parentheses ().

jsCopyEditfunction add(a, b) {
  return a + b;
}

console.log(add(2, 3)); // 5

B. Method Invocation (Object Context)

When a function is a method of an object, this refers to the object.

jsCopyEditconst user = {
  name: "Alice",
  greet: function() {
    console.log("Hi, I'm " + this.name);
  }
};

user.greet(); // Hi, I'm Alice

C. Constructor Invocation (new)

When using the new keyword, this refers to a new object being created.

jsCopyEditfunction Person(name) {
  this.name = name;
}

const p = new Person("Tom");
console.log(p.name); // Tom

D. Indirect Invocation: call() and apply()

Allows you to set this manually.

jsCopyEditfunction sayName() {
  console.log(this.name);
}

const person = { name: "Dave" };

sayName.call(person);  // Dave
sayName.apply(person); // Dave

call() passes arguments one by one, apply() takes them in an array.


E. Arrow Function Invocation

Arrow functions don’t have their own this β€” they inherit it from the enclosing context.

jsCopyEditconst person = {
  name: "Emma",
  greet: () => {
    console.log("Hi, I'm " + this.name);
  }
};

person.greet(); // ⚠️ "Hi, I'm undefined"

πŸ“Œ 3. IIFE (Immediately Invoked Function Expression)

Runs immediately after being defined.

jsCopyEdit(function() {
  console.log("I run automatically!");
})();

Arrow function version:

jsCopyEdit(() => {
  console.log("Arrow IIFE");
})();

πŸ“Œ 4. Event-Driven Invocation

Functions can be invoked in response to events (e.g. clicks):

jsCopyEditdocument.getElementById("btn").onclick = function() {
  alert("Button clicked!");
};

πŸ“Œ 5. Timer-Based Invocation

Invoke a function after a delay or repeatedly.

jsCopyEditsetTimeout(function() {
  console.log("Runs after 2 seconds");
}, 2000);

setInterval(() => {
  console.log("Repeats every 3 seconds");
}, 3000);

πŸ§ͺ Practice Challenges

  1. Define and invoke a function welcome() that prints “Welcome!”.
  2. Create an object with a method that says "My name is <name>".
  3. Use call() to invoke a function with a custom this.

🧠 Summary Table

Invocation TypeExamplethis Value
SimplemyFunc()undefined or window in non-strict
Methodobj.method()obj
Constructornew MyFunc()new object
call() / apply()func.call(obj)manually set to obj
IIFE(function() {})()window (non-strict)
Arrow Function(() => {})()inherited from lexical scope

Would you like:

  • πŸ“„ A PDF version of this tutorial?
  • πŸ’» An interactive JSFiddle or CodePen?
  • 🧠 A mini quiz on invocation types?