0

I know this question falls in the realm of "basics", however I'd like to understand the inner workings of the language.

My question is:
Do operators 'return' the expression's value by default after evaluation?
'return' as in if we were to write:

//some operation using == < > etc...
return result;
  • 2
    Yes and no. We say `foo === bar` *evaluates* to `true` or `false`. The basic idea is that when the computer finds an expression, it is evaluated, then replaced with the final value. This means you can do `const result = foo === bar;` for instance. This might look weird at first, but right of the `=` is an expression that evaluates to true or false, which is then assigned to the const. The same thing happens when you do `const result = fn(...);`, the function is called and the function call is "replaced" with the returned value, again assigning it to the const. –  May 15 '22 at 08:21
  • In short, you can replace `if (foo === bar) return true; else return false;` with `return foo === bar;` and you can replace `if (foo == true)` with `if (foo)`, but rather than saying that an expression "returns" a value I'd say an expression evaluates to its value. –  May 15 '22 at 08:24
  • I definitely get your point, however while studying about "filter()" method, I ran into this snippet: "let someUsers = users.filter(item => item.id < 3);" My understanding was that there needed to be a return statement, which is why I asked this question :) – Abdul-Qader Haddad May 15 '22 at 08:26
  • 1
    I see, that's the short version of an arrow function. If the arrow function only has a single statement, you can remove the `{ }` and the `return`. Especially in callbacks to functions like filter() or sort() you often only see `x => expression`. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#basic_syntax –  May 15 '22 at 08:31
  • Aha! finally makes sense! I guess I need to brush up on Arrow Functions :) Thanks a ton Chris, and thanks Ivan, really appreciate the help. – Abdul-Qader Haddad May 15 '22 at 08:35

1 Answers1

1

There is a slight difference.

foo===bar does not return anything, it only calculates a boolean value.

You can combine this with a return statement, foo===bar to return true if foo == bar, and false otherwise.

if (foo === bar){return true} ONLY returns true if the two are equal, it would return nothing if foo does not equal bar.

  • 1
    Turns out OP is actually asking about [arrow functions with a concise body](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#basic_syntax). –  May 15 '22 at 08:34
  • Yep, next time I should include everything in the question. – Abdul-Qader Haddad May 15 '22 at 08:37