JavaScript OR (||) variable assignment explanation

后端 未结 12 2417
北恋
北恋 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:04

    Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.

    f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:

    alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
    
    0 讨论(0)
  • 2020-11-21 07:07

    This is made to assign a default value, in this case the value of y, if the x variable is falsy.

    The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

    The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

    For example:

    "foo" || "bar"; // returns "foo"
    false || "bar"; // returns "bar"
    

    Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

    0 讨论(0)
  • 2020-11-21 07:11

    Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.

    The following values are considered falsy in JavaScript.

    • false
    • null
    • "" (empty string)
    • 0
    • Nan
    • undefined

    Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

    false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
    

    The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

    1 && [] && {} && true && "World" && null && 2010 // null
    

    The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

    The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

    var a = false;
    var b = a || "Hello";
    

    You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

    var messages = 0;
    var newMessagesText = "You have " + messages + " messages.";
    var noNewMessagesText = "Sorry, you have no new messages.";
    alert((messages && newMessagesText) || noNewMessagesText);
    

    Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".

    0 讨论(0)
  • 2020-11-21 07:13

    There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.

    This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).

    0 讨论(0)
  • 2020-11-21 07:13

    According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

    He also suggests another use for it (quoted): "lightweight normalization of cross-browser differences"

    // determine upon which element a Javascript event (e) occurred
    var target = /*w3c*/ e.target || /*IE*/ e.srcElement;
    
    0 讨论(0)
  • 2020-11-21 07:14

    See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

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