2

What the difference between these two code snippets?

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

and this one:

const Article = (article) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

The only difference is curly brackets in arrow function parameters list... but it have different behavior... in first example article accessable as a plain object... but in the second one, article accessable like some kind of getter or something like that...

Dmytro Medvid
  • 4,988
  • 3
  • 25
  • 29

2 Answers2

3

This is using the destructuring syntax of es6.

Essentially Article is expecting an object. Which is then being destructured into new properties.

Your first item:

const Article = ({article}) => {
  return ( 
    <article key={article.id}>
      <a href={article.link}>{article.title}</a>
      <p>{article.description}</p>
    </article>
 );
};

Is equivalent to:

const Article = (props) => {
  const article = props.article;
  return ( 
    <article key={article.id}>
      <a href={article.link}>{article.title}</a>
      <p>{article.description}</p>
    </article>
 );
};

The mozilla developer network has a great article on both array/object destructuring forms: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

ctrlplusb
  • 12,847
  • 6
  • 55
  • 57
2

It's an ES6 feature for destructuring arrays and objects.

http://es6-features.org/#ParameterContextMatching

Meow
  • 1,610
  • 1
  • 14
  • 18
  • Thanks! Now I see it... missed something... One more link about the issue: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Dmytro Medvid May 31 '16 at 11:40