Skip to content

How to invoke a function in JavaScript

  • by

To invoke a function in JavaScript, you need to call it by its name followed by parentheses () that contain any necessary arguments. This can be done with functions that take parameters or those that don’t take any arguments.

Here’s the basic syntax:

functionName(argument1, argument2, ...);

For example, if you have a function called sayHello that takes no arguments, you would invoke it like this:

sayHello();

If you have a function called addNumbers that takes two arguments, you would invoke it like this:

addNumbers(2, 3);

Note that if the function does not require any arguments, the parentheses are still required. Also, if the function returns a value, you can assign the return value to a variable:

var result = addNumbers(2, 3);

Invoke a function in JavaScript example

Simple example code.

// Define a function
function greet(name) {
  console.log(`Hello, ${name}!`);
}

// Invoke the function
greet('John');

Output:

How to invoke a function in JavaScript

In this example, we define a function called greet that takes one parameter, name. The function simply logs a message to the console using the console.log() function. Then, we invoke the function with the argument 'John', which will output Hello, John! to the console.

Another example

Let’s see how to invoke a function without any arguments.

// Define a function
function sayHello() {
  console.log('Hello!');
}

// Invoke the function
sayHello();

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading