if statement - JavaScript, how to continue expression on the next line - Stack Overflow

Is there a way to continue expression on the next line in JS?const result = 'one' ? 1 :'

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  

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  
Share edited Aug 4, 2019 at 0:01 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Aug 3, 2019 at 23:55 Alex CraftAlex Craft 15.5k14 gold badges90 silver badges156 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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
)

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
);

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
);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744922409a4601213.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信