This content originally appeared on DEV Community and was authored by Naftali Murgor
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.
This content originally appeared on DEV Community and was authored by Naftali Murgor
Naftali Murgor | Sciencx (2022-02-08T16:28:14+00:00) ES6: Default parameters explained. Retrieved from https://www.scien.cx/2022/02/08/es6-default-parameters-explained/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.