Thursday, July 29, 2021

Destructure arrays and objects

Typically, to show specific items within an array, you’d use the array name followed by its key number:

const myArray = ["item1", "item2", "item3"];
console.log(myArray[2]);

This will print: item3

Sometimes though some devs may find it useful to work with variable names instead of key numbers:

const [,,myItem3] = ["item1", "item2", "item3"];
console.log(myItem3);

This will also print: item3

You may also find this in app components that have multiple property names (object keys):

function App2(props) {
  return (
    <>
      <h1>{(props.title)}</h1>
      {(props.access) ? <GrantAccessMessage /> : <DeniedAccessMessage />};
    </>
  )
}

export default App2;

Typical function uses the props object + property name (or object key):

The deconstructed one only uses property names:

function App2({title, access}) {
  return (
    <>
      <h1>{(title)}</h1>
      {(access) ? <GrantAccessMessage /> : <DeniedAccessMessage />};
    </>
  )
}

export default App2;

No comments:

Post a Comment