Function

NayemulAlam
2 min readNov 7, 2020

.

Set Default parameter on function

Sometimes when we use some function we need to set default values for their parameter’s. If you set two parameters and user set only one value then the result will be show as NaN (Not a Number).That’s why we need to use default parameter.

Example:

function withDefaultParam(a = 0, b = 0){ 
return a+b;
}
console.log(withDefaultParam(5,6));
// output 11
function withOutDefaultParam(a,b){
return a+b;
}
console.log(withOutDefaultParam(5))
// output NaN

Arrow Function

Arrow functions were introduced in ES6.Arrow functions allow us to write shorter function syntax. If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword. If you have parameters, you pass them inside the parentheses. In fact, if you have only one parameter, you can skip the parentheses as well.

// before arrow funtion //const name = function() {
return "Hello Sifat!";
}
// after arrow funtion //const name = () => {
return "Hello Sifat!";
}
// single statement arrow function //const name = () => "Hello World!";// funtion with bracketless parameter //hello = val => "Hello " + val;

The Spread Operator

When we need to spread our array or something we can use this spread operator. Three dots are using for spread(…).

let animal = [Lion, Fish, Cow]let food = [...animal, Meat, Water, Grass]console.log(food) //output Lion, Fish, Cow, Meat, Water, Grass //

Anonymous Parameters

Normally we passes few parameters on a function and can work with them. But when we need to pass so many parameter through the function it will be more complicated for us, because we need to write so mane parameter name an it’s like so boring. We can use rest parameter for the problem .

const name = (...num) => {let sum = 0;for( let i of num ) {sum += i;
}
console.log(sum)
}
name(1,2,3,4,5,6,7,8,9,100)// output 145 //

Block level function

When we declare let or const variable in a function we could not access them from outside. This called block level funtion.

function blockDec(){
let localVar = "Nayemul";
console.log(localVar);
}
console.log(localVar)
blockDec()// you will get error

--

--