Javascript Function

Introduction

Javascript functions are objects.

Each function is an instance of the Function type.

Function type has properties and methods.

Javascript function names are pointers to function objects.

Functions are typically defined using function-declaration syntax:

function sum (num1, num2) { 
   return num1 + num2; 
} 

In this code, a variable sum is defined and initialized as a function.

The function-declaration syntax is almost equivalent to using a function expression:

let sum = function(num1, num2) { 
   return num1 + num2; 
}; 

There is a semicolon after the end of the function.

The following code uses the "arrow" function syntax:

let sum = (num1, num2) => { 
   return num1 + num2; 
}; 

The final way to define functions is to use the Function constructor.

It accepts any number of arguments.

The last argument is considered to be the function body.

The previous arguments enumerate the new function's arguments.

let sum = new Function("num1", "num2", "return num1 + num2");   // not recommended 



PreviousNext

Related