Best Way for Conditional Variable Assignment

后端 未结 12 1116
一个人的身影
一个人的身影 2021-01-31 02:26

Which is the better way for conditional variable assignment?

1st method

 if (true) {
   var myVariable = \'True\';
 } else {
   var myVariable = \'False\         


        
12条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 02:58

    An alternative way of doing this is by leveraging the ability of logical operators to return a value.

    let isAnimal = false;
    let isPlant = true;
    
    let thing = isAnimal && 'animal' || isPlant && 'plant' || 'something else';
    
    console.log(thing);
    

    In the code above when one of the flags is true isAnimal or isPlant, the string next to it is returned. This is because both && and || result in the value of one of their operands:

    • A && B returns the value A if A can be coerced into false; otherwise, it returns B.
    • A || B returns the value A if A can be coerced into true; otherwise, it returns B.

    Answer inspired by this article: https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript

    PS: Should be used for learning purposes only. Don't make life harder for you and your coworkers by using this method in your production code.

提交回复
热议问题