Skip to content

13 Function Features

Biswajit Sundara edited this page May 1, 2023 · 2 revisions

1. Default parameters

  • In Java Script we will have to provide all the arguments/parameters while calling the function.
  • The missing values are assigned with undefined.
  • If we use in any calculation then its going to end up with NaN etc.

Without default parameter

const annualSalary = (sal,bonus) =>{
   return sal+bonus;
}
//If we call this, it will print NaN
//console.log(annualSalary(2000)); 

//This will work fine
console.log(annualSalary(2000,500));

With default parameter

const annualSalary = (sal,bonus=0) =>{
    return sal+bonus;
 }
 console.log(annualSalary(2000));
 console.log(annualSalary(2000,500));

With default object parameter

const annualSalary = (sal,bonus = {teamBonus: 0,employeeBonus: 0}) => {
  return sal + bonus.teamBonus + bonus.employeeBonus;
};

console.log(22000, { teamBonus: 1000, employeeBonus: 200 });

2. Default parameter

A way to capture any remaining arguments in a function call and pass them to an array.

function greet(name = 'World') {
  console.log(`Hello, ${name}!`);
}

greet(); // Output: "Hello, World!"
greet('John'); // Output: "Hello, John!"

Clone this wiki locally