0

What are the differences between the two code snippets below, including any advantages or disadvantages of one over the other?

const a = (b) => (
    b = b * 10,
    console.log(b),
    true && console.log('true'),
    false && console.log('false'),
    b = b * 2
)
const a = (b) => {
    b = b * 10;
    console.log(b);
    if(true) console.log('true');
    if(false) console.log('false');
    b = b * 2;
    return b;
}

I recently saw a project in which the dev used parentheses in virtually every situation and wanted to understand that better.

TrevTheDev
  • 2,616
  • 2
  • 18
  • 36
  • One is readable, reasonable, and can contain statements. The other is obfuscation by abusing the comma operator and logical and. A deobfuscation tool i wrote has cases for that use of comma operator and logical and - it would autoconvert the first to the second snippet. – ASDFGerte Aug 14 '20 at 04:13
  • 1
    The 2nd example's parentheses either invoke a function (with arguments, although not all functions require arguments) or provides a condition to an `if` statement. The 1st example surrounds an expression with parentheses (which you always can, and sometimes must, do). This expression uses the comma operator (See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). One reference related to JS expressions is: https://leanpub.com/javascriptallongesix/read#leanpub-auto-prelude-values-and-expressions-over-coffee. – Cat Aug 14 '20 at 04:33
  • @Ferin Patel I did see that question, but it doesn't cover the commas used to separate lines of code, so those answers are incomplete. – TrevTheDev Aug 14 '20 at 07:11
  • @Cat, thank you that is a useful link that clarifies this for me. – TrevTheDev Aug 14 '20 at 07:15
  • @Ferin Patel why did you close this question? The other question is not the same as this question. E.g. which version is faster, which version is clearer, what are the side effects if any of the first one. – TrevTheDev Aug 14 '20 at 07:24

0 Answers0