0

This is probably basic JS stuff but please what is the difference between

app.get("/api/products/1", (req, res) => {
  const singleProduct = products.find((product) => {
    product.id === 1;
  });
  res.json(singleProduct);
});

AND


app.get("/api/products/1", (req, res) => {
  const singleProduct = products.find((product) => product.id === 1);
  res.json(singleProduct);
});

They look the same to me, the former is me trying to code ahead of the instructor and I was not getting any JSON response on the browser, while the latter is the instructor's code which he got the JSON response

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jay Jay
  • 33
  • 8
  • 1
    The second has an implicit return, the first does not. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#description – Nicholas Tower Jun 30 '23 at 19:11
  • 1
    `products.find((product) => {product.id === 1;});` always returns `undefined`. – Unmitigated Jun 30 '23 at 19:12
  • The first one (currently incorrect example), to be properly formatted should use a `return product.id === 1;` - and it will be equal to the second (valid) example which uses implicit return. – Roko C. Buljan Jun 30 '23 at 19:13
  • The first code returns undefined and the second code returns true or false depending on weather `product.id` equals `1` – slebetman Jun 30 '23 at 19:20

1 Answers1

2

The first code will always returns undefined. Because it's missing a return inside the function. You should know that when a function doesn't have return keyword it's by default returning undefined. And if you using curly braces in function, you have to explicitly specify the return keyword if you want to return a value.

  const singleProduct = products.find((product) => {
    return product.id === 1;
  });

The second code works because when you don't use curly braces JS implicitly returns the result of the comparison product.id === 1.

XMehdi01
  • 5,538
  • 2
  • 10
  • 34