Types of functions in ES6

Function Expression

let sayHello=function(){
console.log("Hello, welcome to capscom technology");
}

sayHello();

Function expression with return statement

let sayHello=function(){
return "Hello, welcome to capscom technology";
}

console.log(sayHello());

Parametrised function expression

let sum=function(a, b){
let c;
c=a+b;
return c;
}

console.log( sum(100, 200) );

callback function

function check_number(n, successMessage, failedMessage){
			if(n%2==0){
				successMessage();
			}
			else{
				failedMessage();
			}
		}
		function successMessage(){
			alert("even number");
		}
		function failedMessage(){
			alert("odd number");
		}
		check_number(13, successMessage, failedMessage);
Note: successMessage, failedMessage are called callback function or just callback

Anonymous function

A function declared with no name is called anonymous function

document.addEventListener("keyup", function(e){
let code=e.keyCode;
alert(code);
});
This declared function with no name is called anonymous function

Arrow function

Arrow function contain concise syntax than other function, and it is called arrow function, because it look like arrow.

let sayHello=()=>console.log("Welcome to capscom technology");
sayHello()

Key points 

  1. If arrow function has no parameters, paranthesis will be empty
    let sayHello=()=>console.log("Welcome to capscom technology");
    sayHello()
  2. If arrow function has one parameter, paranthesis can be omitted.
    let areaOfCircle = r => 3.14*r*r;
    console.log(areaOfCircle(2.5))
  3. Arrow function always return value implicitly, there is no need to write return statement

Arrow function with multiline syntax

When an arrow function contain multiline syntax, there will need to return value explicitly.

let fact=n=>{
	let f=1;
	for(i=n; i>=1; i=i-1){
		f=f*i;
	}
	return f;
}
© 2016 - 2022, All Rights are Reserved.