What it exactly means in Javascript (assigning variable)

This question already has an answer here:

  • Is there a “null coalescing” operator in JavaScript? 8 answers
  • What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript? 7 answers

  • The || is effectively working like a SQL COALESCE statement.

    var x = y || z;
    

    means:

    if y evaluates to a "truthy" value, assign y to x .

    if y evaluates to a "falsy" value, assign z to x .

    See http://11heavens.com/falsy-and-truthy-in-javascript for more detail on "truthy/falsy" (or just google it).


    The || is an or operator.

    It basically means if variable is undefined, it will assign variable to a new object literal.

    https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators#Logical_operators


    || does mean OR here:

    var x = 5
    var x = x || {} //If v is defined, v = v, else v = {} (new, empty, object).
    //x = 5 since x already was defined
    
    var y = y || {}
    //y = {} since y was undefined, the second part is run.
    
    链接地址: http://www.djcxy.com/p/73364.html

    上一篇: 我们在JavaScript中有一个更简单的三元运算符吗?

    下一篇: 它在Javascript中的意义(分配变量)