default parameters are arguments to function change to a default value if arguments value is not passed to function.

It is introduced in javascript with ES6/ES2015 specification.

Before the ES6 Version,

Functions are written in such a way that function body checks if a parameter exists or not

For example,

We have a function declared with two arguments. And the caller send two arguments

function add(first, second) {
  first = typeof first !== 'undefined' ? first : 0; //line1
  second = typeof second !== 'undefined' ? second : 0; //line2

  return first+second;

}
console.log(add(10,20));//30
console.log(add());//0

if the caller passes two arguments to the function, add(10,20) function returns the expected results.

if no arguments are passed to function, We have to handle check for the existence of variable type and undefined and assign with the default value.

To avoid this checking the value of the argument exists, ES6 introduced default parameters.

How to add default parameters to functions in javascript

In the function declaration, you define the function with arguments is assigned with a default value. It simplified the checking of undefined values for arguments and clean code.

Syntax

function  name(arguments=defaultvalue){

}

Here is an example code

function add(first=0, second=0) {
 
  return first+second;

}
console.log(add(10,20));//30
console.log(add());//0

It need not be default argument values, but also expressions and functions

ES6 Default expressions to functions

Functions can also be passed with javascript expressions. expressions are evaluated at runtime.

Here is an example of default javascript expressions in functions

function add(first=1, second=first+1) {
 
  return first+second;

}
console.log(add(10,20));//30
console.log(add());//3

ES2015 default function parameters as arguments in a function

ES6 allows not only default parameters values and expressions, but also allows Function as default value passed to arguments.

Here is an example

function hello(message = getMessage()) {
 return message;
}

function getMessage() {
  return 'Hello World';
}

console.log(hello("Welcome")) //Welcome
console.log(hello()) //Hello World