In my years of JS development I've seen the following examples:
let a = () => console.log("a");
let b = () => { console.log("b"); }
let c = () => (console.log("c"));
I know the difference between the first two options, but the last one always seem'd a little off to me. I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console logs.
And also this:
let c = () => (1, 2, 3, 4 ,5);
let x = c(); // 5
I've searched about this way of defining function bodies, yet I'm not satisfied with what I have found since every example I've stumbled on was poorly explained.
Can anyone please explain to me a bit more in-depth the difference between the three examples, and also what's special about the last one?
Thanks in advance.
CodePudding user response:
let c = () => (console.log("c"))
I know the difference between the first two options, but the last one always seem'd a little off to me.
Arrow syntax allows you to return the value of the expression directly without having to enclose in curly braces and using a return
statement. In the example above, enclosing the value (returned by console.log
) in brackets does not change its value.
And also this:
let c = () => (1, 2, 3, 4, 5);
What you are seeing is the comma operator in action. It will return the value of the last operand, which is why c
returns 5
.
I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console log
In this case, both expressions are evaluated, and thus both strings are logged. However, the expression yields a value of undefined
, since console.log
returns undefined
.
CodePudding user response:
First of all, you're talking specifically about arrow (=>
) functions. Traditional functions must have a body enclosed in { }
.
An arrow function can have a traditional body enclosed in { }
. It can also have a single expression as its body, in which case the result of evaluating the expression is implicitly the return value. Given that, note that any expression in JavaScript in any context can be enclosed in parentheses ( )
and the value is the same as the enclosed expression.
The comma effect is the operator in the JavaScript expression grammar ,
, which allows disparate expressions to be chained together into a list that, syntactically, is still a single expression. The comma operator is useful sometimes because expressions can have side-effects; for example, a function call is an expression, and a function call may do almost anything. The value of a list of expressions in a comma operator list is the value of the last one of the expressions after evaluation.