How to call a function in javascript

JavaScript functions are blocks of code that perform a specific task and can be executed when they are called. Functions can be defined and called in several ways in JavaScript.

Here are the ways to define and call functions in JavaScript:

  1. Function Declaration

A function declaration is defined using the function keyword followed by the function name, a list of parameters within parentheses, and a block of code to be executed, enclosed within curly braces {}.

Here’s an example of a simple function declaration:

function greet(name) {
console.log("Hello " + name);

To call this function, you just need to write the function name followed by its arguments within parentheses:


This would output "Hello John" to the console.

  1. Function Expression

A function expression is defined by assigning an anonymous function (a function without a name) to a variable.

Here’s an example of a function expression:

var greet = function(name) {
console.log("Hello " + name);

To call this function, you can use the variable name:


This would output "Hello Jane" to the console.

Note that function expressions are not hoisted, meaning that they are not available to be called before they are defined in the code. In contrast, function declarations are hoisted, which means they can be called before they are defined.

  1. Arrow Function Expression

An arrow function expression is a shorthand for writing function expressions. It uses the => syntax instead of the function keyword to define the function.

Here’s an example of an arrow function expression:

var greet = (name) => {
console.log("Hello " + name);

To call this function, you can use the variable name just like in function expressions:


This would output "Hello Bob" to the console.

  1. Callback Functions

Callback functions are functions that are passed as arguments to other functions and are executed when a certain event occurs or a certain condition is met.

Here’s an example of a callback function:

function greeting(name, callback) {
console.log("Hello " + name);

function sayGoodbye() {

greeting("David", sayGoodbye);

In this example, sayGoodbye is a callback function that is passed as an argument to the greeting function. When the greeting function is called, it outputs "Hello David" and then calls the sayGoodbye function, which outputs "Goodbye!" to the console.

  1. Constructor Functions

Constructor functions are used to create objects in JavaScript. They are defined with the function keyword followed by the constructor name with a capital letter.

Here’s an example of a constructor function:

function Person(name, age) { = name;
this.age = age;

var john = new Person("John", 30);
console.log(; // outputs "John"

Leave a Reply

Your email address will not be published. Required fields are marked *