JavaScript OR (||) variable assignment explanation

后端 未结 12 2412
北恋
北恋 2020-11-21 06:41

Given this snippet of JavaScript...

var a;
var b = null;
var c = undefined;
var d = 4;
var e = \'five\';

var f = a || b || c || d || e;

alert(f); // 4
         


        
12条回答
  •  粉色の甜心
    2020-11-21 07:02

    This question has already received several good answers.

    In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.

    Using this technique is not good practice for several reasons; however.

    1. Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.

    2. Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.

    3. Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:

      () ? value 1: Value 2.

    Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.

    var a;
    var b = null;
    var c = undefined;
    var d = 4;
    var e = 'five';
    
    var f =  ( a ) ? a : 
                    ( b ) ? b :
                           ( c ) ? c :
                                  ( d ) ? d :
                                          e;
    
    alert(f); // 4
    

提交回复
热议问题