Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Function Invocation




JavaScript function invocation refers to the process of executing a function. There are various ways to invoke a function in JavaScript:

  1. Function Call: The most common way to invoke a function is by using its name followed by parentheses (). If the function accepts arguments, they can be passed within the parentheses.

  2.           function greet(name) {
                return "Hello, " + name + "!";
            }
            
            console.log(greet("John")); // Output: Hello, John!
             

  3. Method Invocation: If a function is a property of an object, it is called a method. To invoke a method, you use dot notation (.) followed by the method name and parentheses.

  4.           const person = {
                name: "Alice",
                greet: function() {
                    return "Hello, " + this.name + "!";
                }
            };
            
            console.log(person.greet()); // Output: Hello, Alice!
             

  5. Constructor Invocation: JavaScript allows you to create objects using constructor functions. When you use the new keyword with a constructor function, it creates a new object and invokes the constructor function.

  6.           function Person(name) {
                this.name = name;
                this.greet = function() {
                    return "Hello, " + this.name + "!";
                };
            }
            
            const person = new Person("Bob");
            console.log(person.greet()); // Output: Hello, Bob!
             

  7. Indirect Invocation: You can use methods like call() and apply() to indirectly invoke functions, allowing you to specify the context (this) and arguments.

  8.           function greet() {
                return "Hello, " + this.name + "!";
            }
            
            const context = { name: "Sarah" };
            console.log(greet.call(context)); // Output: Hello, Sarah!
             

  9. Immediately Invoked Function Expression (IIFE): An IIFE is a function that is declared and invoked immediately. This pattern is often used to create a private scope.

  10.           (function() {
                console.log("I'm invoked immediately!");
            })();
             

    Each of these methods has its use cases and implications, and understanding them is essential for writing effective JavaScript code.





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java