[removed] || instead of IF statement - is this legal and cross browser valid?

后端 未结 10 934
忘掉有多难
忘掉有多难 2020-12-23 20:43

It seems that:

if (typeof a == \'undefined\') {
    a = 0;
}

and

(typeof a != \'undefined\') || (a = 0)

h

相关标签:
10条回答
  • 2020-12-23 21:10

    Why not something more simple, like:

    a = a || 0;
    

    or

    a = a ? a : 0;
    

    In both of these cases, you can also clearly see that something is being assigned to a, right at the start of the line, without resorting to reading the whole thing, and figuring out if there are any game-changing function-calls happening on either the left or right side... or figuring out what both sides do, in general, to decide how many potential program-wide changes there might be.

    If you need to include the whole type-check, it's still not that large.

    a = (typeof a !== "undefined") ? a : 0;  // [parentheses are there for clarity]
    
    0 讨论(0)
  • 2020-12-23 21:10

    You can use:

    a = typeof(a) !== "undefined" ? a : 0; 
    
    0 讨论(0)
  • 2020-12-23 21:11

    I think that it is terrible to use constructions like this. It works but code not readable. If you want to write one-line conditions you can start using CoffeeScript and write:

    a = 0 if (typeof a == 'undefined');
    

    In your case, when you have one variable in condition and assignment, use one-line javascript ternary operator:

    a = (typeof a == 'undefined') ? 0 : a;
    
    0 讨论(0)
  • 2020-12-23 21:11
    (typeof a != 'undefined') || (a = 0)
    

    is an expression. But one of its subexpressions

    (a = 0)
    

    is an assignment. So essentially, this is an expression with a side effect. Statements (especially those that are expessions), that have side effects are typically one of the first things you learn not to do in an introductory coding class. So why do it simply because it only takes one line?

    0 讨论(0)
  • 2020-12-23 21:15

    Moreover I suppose it would impact performances because

    (typeof a != 'undefined') || (a = 0)
    

    is composed of two test (even if we don't care about the second one).

    Whereas

    if (typeof a == 'undefined') {
        a = 0;
    }
    

    contains only one test

    0 讨论(0)
  • 2020-12-23 21:16

    I hated "|| instead of IF" for years.

    I finally got used to it and now I love it.

    I also like using && in the same way.

    I've found it is much easier to read others terse code if you adopt terse practices yourself.

    Totally understand where others are coming from though. Been there myself.

    0 讨论(0)
提交回复
热议问题