點燈坊

失くすものさえない今が強くなるチャンスよ

Always Passing Object to Function

Sam Xiao's Avatar 2021-11-20

Object Destructuring was introduced by ECMAScript 2015. Using it with function argument, we can implement Pass By Name feature in ECMAScript.

Version

ECMAScript 2015

Pass by Value

let f = (hi, name) => `${hi} ${name}`

f ('Hello', 'Sam') // ?
  • Before ES2015, if the function has multiple arguments, we have to pass them by value with the correct sequence
  • For readability concerned, we don’t know the meaning of each argument we pass

object000

Pass by Name

let f = ({ hi, name }) => `${hi} ${name}`

f ({ hi: 'Hello', name: 'Sam'}) // ?
  • With Object Destructuring provided by ES6, we can replace multiple arguments with one Object and directly destructure them on the argument
  • When calling function, we have to provide an Object with key and value, and this improves the readability of each argument we pass

object001

Default Value

let f = ({ hi = 'Hello', name }) => `${hi} ${name}`

f ({ name: 'Sam'}) // ?

We can provide the argument’s default value, so users may not have to provide Object with those keys.

object002

Optional Argument

let f = ({ hi = 'Hello', name = 'World' } = {}) => `${hi} ${name}`

f () // ?

If all arguments are optional, we have to do the following steps :

  • Make each argument with a default value
  • Make the whole object with default empty Object

object003

Conclusion

  • Since ECMAScript is a multi-paradigm language, there are many coding styles in ECMAScript.
  • For arguments of a function, we may have many styles :
    • A function with multiple arguments
    • A function with only one object as an argument, destructuring to multiple arguments
    • Acurried function to implement multiple arguments