Alex Craft
Alex Craft

Reputation: 15336

JavaScript, how to continue expression on the next line

Is there a way to continue expression on the next line in JS?

const result = 'one' ? 1 :
  'two' ? 2 :
          3

turn it into

const result = \
  'one' ? 1 :
  'two' ? 2 :
          3

and turn this

return condition1 && 
  condition2 && 
  condition3

into

return \
  condition1 && 
  condition2 && 
  condition3  

So it would looks better?

It's possible to do it like that but I hope there are better way

return true &&
  condition1 && 
  condition2 && 
  condition3  

Upvotes: 2

Views: 2380

Answers (3)

exside
exside

Reputation: 3884

This is very much about personal preference, here's how I like to write those:

const result = 
  "one"
  ? 1
  : ("two"
    ? 2
    : 3);

return (
  condition1
  && condition2
  && condition3
);

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

Yes - just use parentheses for the return one:

return (
  condition1 &&
  condition2 &&
  condition3
);

If you leave a newline after the return keyword, it'll return undefined.

Your ternary operator can be used as-is, but consider also using parentheses to decrease confusion:

const result = 
  "one" ? 1 : (
  "two" ? 2 : 3
);

Upvotes: 3

Patrick Roberts
Patrick Roberts

Reputation: 51846

Your first desired snippet

const result =
  'one' ? 1 :
  'two' ? 2 :
          3

is already allowed, but due to automatic semicolon insertion (ASI), the return statement must be written as:

return (
  condition1 && 
  condition2 && 
  condition3
)

Upvotes: 5

Related Questions