J

JavaScript Handbook

Clean • Professional

Function Invocation in JavaScript – How to Call Functions

1 minute

Function Invocation in JavaScript

Function invocation is how you execute a function in JavaScript. The context of the call (the value of this) depends on how the function is invoked. Understanding invocation types is crucial for writing predictable and maintainable code.

learn code with durgesh images

Direct Invocation

Direct invocation occurs when a function is called on its own, not as part of an object. In this case, the this keyword behaves differently depending on strict mode:

  • Non-strict mode: this refers to the global object (window in browsers, global in Node.js).
  • Strict mode: this is undefined.

Example:

// Direct function invocation
function greet(name) {
  console.log(`Hello, ${name}!`);
  console.log(this); // global object in non-strict, undefined in strict
}

greet("Alice");
// Hello, Alice!
// Window { ... } (non-strict mode)
// undefined (strict mode)

Method Invocation

Method invocation occurs when a function is called as a property of an object. Here, the this keyword refers to the object owning the method.

  • this always points to the object on which the function was called.
  • Using arrow functions as object methods changes the behavior of this (lexical this).

Example:

const user = {
  name: "Bob",
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  }
};

user.greet(); // Hello, Bob!

Example with Arrow Function:

const user = {
  name: "Charlie",
  greet: () => {
    console.log(`Hello, ${this.name}!`);
  }
};

user.greet(); // Hello, undefined!
// Arrow functions do NOT have their own `this`, they inherit it from the parent scope

Summary Table

Invocation TypeSyntaxthis BehaviorExample Output
Direct Invocationfunc()Global object (non-strict) or undefined (strict)"Hello, Alice!"
Method Invocationobj.func()Refers to the object (obj)"Hello, Bob!"


Article 0 of 0