JavaScript OR (||) variable assignment explanation

后端 未结 12 2415
北恋
北恋 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 06:47

    It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

    var x = '';
    var y = 'bob';
    var z = x || y;
    alert(z);
    

    Will output 'bob';

    0 讨论(0)
  • 2020-11-21 06:49

    It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.

    it's the same as

    if(x)
      z = x;
    else
      z = y;
    

    It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.

    0 讨论(0)
  • 2020-11-21 06:54

    Return output first true value.

    If all are false return last false value.

    Example:-

      null || undefined || false || 0 || 'apple'  // Return apple
    
    0 讨论(0)
  • 2020-11-21 06:55

    Its called Short circuit operator.

    Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.

    It could also be used to set a default value for function argument.`

    function theSameOldFoo(name){ 
      name = name || 'Bar' ;
      console.log("My best friend's name is " + name);
    }
    theSameOldFoo();  // My best friend's name is Bar
    theSameOldFoo('Bhaskar');  // My best friend's name is Bhaskar`
    
    0 讨论(0)
  • 2020-11-21 06:58

    It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.

    For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:

    function doSomething(data, callback) {
        callback = callback || function() {};
        // do stuff with data
        callback(); // callback will always exist
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题