日本語の晴見

日本語は学べば学ぶほど面白い

Destructuring the Function Parameter

Sam Xiao's Avatar 2022-11-22

Sometimes we may get an Object with an Array on the parameter. We can use Object and Array destructuring together for the function parameter.

Version

ECMAScript 2015

Traditional Way

let data = {
  names: ['Sam', 'Tome', 'Ken']
}

let f = x => {
  let name = x.names[0]
  return 'Hello ' + name
}

f(data) // ?
  • Use . and [] to get value of an Object with an Array

param000

Object and Array Destructuring

let data = {
  names: ['Sam', 'Tome', 'Ken'],
}

let f = ({ names: [name, _] }) => {
  return `Hello ${name}`
}

f(data) // ?
  • Use Object Destructuring to destructure the property of the Object
  • Use Array Destructuring to destructure to the element of the Array, _ for ignoring elements

param001

Conclusion

  • We can use Object Destructuring and Array Destructuring together for Function Parameter