JavaScript Function Invocation

Understanding how to call and execute functions

🚀 What is Function Invocation?

Function invocation means calling or executing a function. In JavaScript, you invoke a function by adding parentheses () after the function name.


// Define a function
function sayHello() {
    return "Hello World!";
}

// Invoke (call) the function
sayHello(); // This executes the function
                                    

Output:

"Hello World!"

Ways to Invoke Functions

📞

Direct Call

Call function by name with ()

myFunction();
🎯

Method Call

Call function as object method

object.method();
âš¡

Immediate Call

Execute function immediately

(function() {
  // code here
})();
🔄

Event Call

Call function on events

button.onclick = myFunction;

🔹 Basic Function Invocation

The most common way to invoke a function:

// Function declaration
function greet() {
    return "Hello there!";
}

// Function invocation
let message = greet(); // Call the function
console.log(message);

// You can also call it directly
console.log(greet());

Output:

Hello there!
Hello there!

🔹 Function with Parameters

Invoking functions with arguments:

// Function with parameters
function addNumbers(a, b) {
    return a + b;
}

// Invoke with arguments
let result1 = addNumbers(5, 3);
let result2 = addNumbers(10, 20);

console.log("5 + 3 =", result1);
console.log("10 + 20 =", result2);

Output:

5 + 3 = 8
10 + 20 = 30

🔹 Method Invocation

Calling functions that belong to objects:

// Object with methods
let calculator = {
    name: "My Calculator",
    add: function(x, y) {
        return x + y;
    },
    multiply: function(x, y) {
        return x * y;
    }
};

// Method invocation
let sum = calculator.add(4, 6);
let product = calculator.multiply(3, 7);

console.log("Sum:", sum);
console.log("Product:", product);

Output:

Sum: 10
Product: 21

🔹 Immediate Function Invocation

Execute a function immediately after defining it:

// IIFE - Immediately Invoked Function Expression
(function() {
    console.log("This runs immediately!");
})();

// IIFE with parameters
(function(name) {
    console.log("Hello, " + name + "!");
})("Alice");

// Arrow function IIFE
(() => {
    console.log("Arrow IIFE executed!");
})();

Output:

This runs immediately!
Hello, Alice!
Arrow IIFE executed!

🧠 Test Your Knowledge

How do you invoke a function named "myFunc"?