Java Script Function Types

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Function Declaration :

function functionName(parameters) {
// code to be executed
}
EX :
function myFunction(a, b) {
return a * b;
}

Function Expressions :
Const X = myFunction(a, b) {
return a * b;
}
Calling above function
let z = x(4, 3);
-----------------------------------------------------------------------
Constructor Function :
Functions can also be defined with a built-in JavaScript function
constructor called Function()

EX : const myFunction = new Function("a", "b", "return a * b");


Calling above function :
let z = myFunction (4, 3);
Function constructors work same as the default function declaration.
The only difference is in the writing.

Self Invoking Function :


Function expressions will execute automatically if the expression is
followed by ()

Ex :
(function () {
let x = "Hello!!";
})();
The function above is an anonymous self-invoking function (function
without name).
Arrow Functions :

Arrow functions allows a short syntax for writing function expressions


i.e. function keyword, the return keyword, and the curly brackets are
not needed.

Normal Function(Function Expression) :

var x = function(x, y) {
return x * y;
}

Arrow function :
const x = (x, y) => { return x * y };

Arrow functions are not hoisted. They must be defined before they are
used.

-----------------------------------------------------------------------

Function Parameters :

JavaScript function definitions do not specify data types for


parameters.

JavaScript functions do not perform type checking on the passed


arguments.

JavaScript functions do not check the number of arguments received.

If a function is called with missing arguments (less than declared),


the missing values are set to undefined.

-----------------------------------------------------------------------

Invoking Function as a method :

In JavaScript you can define functions as object methods.

The following example creates an object (myObject), with two properties


(firstName and lastName), and a method (fullName):

const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName();
Invoking Function with Function Constructor :

If a function invocation is preceded with the new keyword, it is a


constructor invocation.

EX :

function myFunction(arg1, arg2) {


this.firstName = arg1;
this.lastName = arg2;
}

Below is invoking function with Function Constructor


const myObj = new myFunction("John", "Doe");

This will return "John"


myObj.firstName;

You might also like