Default Arguments are parameters passed to to function optionally. If there is no value assigned by caller, these values assigned toa 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 the function body checks if a parameter exists or not
For example,
We have a function declared with two arguments. And the caller has to 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 Set a default parameter value for a JavaScript function
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 parameter 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
Default Values with Destructuring assignment syntax
Destructuring assignment extract the values from array and object, assigned to variables.
//Object declared
const employee = {id: "1", name: "krish"}
// Destruct assignment syntax
const {id:"0", name:"default",salary:5000} = employee
employee
object values are assigned to variables, if no matching property found, It assigned with default values. salary
property is not found, so assigned with 5000