DEV Community

Cover image for ES6: Default parameters explained
Naftali Murgor
Naftali Murgor

Posted on • Updated on

ES6: Default parameters explained

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy ๐ŸŽ–๏ธ • Edited
const myWalletTwo = restoreWallet('0x05417') // json defaults to true if not supplied
Enter fullscreen mode Exit fullscreen mode

This is not correct.

In this case, dumpToJson will be '0x05417' and privateKey will be undefined

Collapse
 
j471n profile image
Jatin Sharma

Exactly we pass default parameters in the end of all the other parameters.

Collapse
 
naftalimurgor profile image
Naftali Murgor

Thanks for the feedback. Will update to fix the error

Some comments have been hidden by the post's author - find out more