Introduction
ES2015(ES6) introduced default parameters. Let’s jump right in and learn about default parameters.
Default parameters
What would happen if we called a function with all or some parameters missing? It turns out JavaScript assigns undefined
to the missing arguments.
Let’s see example in code:
const add = (num1, num2) => num1 + num2
const sum = add(2) // one argument is missing // gets called as 2 + undefined
console.log(sum) // prints NaN
Default parameters allow us to define a default parameter value and will be used when no argument is provided for the paramter during funciong call:
const main = (port = 3000) => {
// possible code ommitted here
}
main() //port will default to value of 3000
main(5000) // call main with 5000
Another dummy example:
const restoreWallet = (dumpToJson=true, privateKey) => {
// posible code omitted
}
const myWallet = restoreWallet(false, '0xFEEDBEEFFEEDBEEF') // dumpToJson supplied as false
const myWalletTwo = restoreWallet('0x05417') // json defaults to true if not supplied
const fetchItems = async (storeName, keys = []) => {
// possible code omitted here
}
const itemStore = await fetchItems('Electronics') // key defaults to an empty array object
Summary
Default parameters allow us to provide a default value for the argument when not supplied during the function call.