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 funcion 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:
// add default parameters at the end of parameter list
const restoreWallet = (privateKey, dumpToJson=true) => {
// posible code omitted
}
const myWallet = restoreWallet('0xFEEDBEEFFEEDBEEF', false) // dumpToJson supplied as false
const myWalletTwo = restoreWallet('0x05417') // dumpToJson defaults to true if not supplied
const fetchItems = async (storeName, keys = []) => {
// possible code omitted here
}
const itemStore = await fetchItems('Electronics') // keys 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.
Default parameters are added at the end of the paremeter list.
Top comments (3)
This is not correct.
In this case,
dumpToJson
will be'0x05417'
andprivateKey
will beundefined
Exactly we pass default parameters in the end of all the other parameters.
Thanks for the feedback. Will update to fix the error
Some comments have been hidden by the post's author - find out more