Shorthand if/else statement Javascript

前端 未结 7 1425
难免孤独
难免孤独 2020-12-07 16:57

I\'m wondering if there\'s a shorter way to write this:

var x = 1;
if(y != undefined) x = y;

I initially tried x = y || 1, but

相关标签:
7条回答
  • 2020-12-07 17:04

    Another way to write it shortly

    bePlanVar = !!((bePlanVar == false));
    
    // is equivalent to
    
    bePlanVar = (bePlanVar == false) ? true : false;
    
    // and 
    
    if (bePlanVar == false) {
        bePlanVar = true;
    } else {
        bePlanVar = false;
    }
    
    0 讨论(0)
  • 2020-12-07 17:07

    Here is a way to do it that works, but may not be best practise for any language really:

    var x,y;
    x='something';
    y=1;
    undefined === y || (x = y);
    

    alternatively

    undefined !== y && (x = y);
    
    0 讨论(0)
  • 2020-12-07 17:07

    Appears you are having 'y' default to 1: An arrow function would be useful in 2020:

    let x = (y = 1) => //insert operation with y here
    

    Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.

    0 讨论(0)
  • 2020-12-07 17:09

    You can try if/else this shorthand method:

    // Syntax
    if condition || else condition
    
    // Example
    let oldStr = "";
    let newStr = oldStr || "Updated Value";
    console.log(newStr); // Updated Value
    
    // Example 2
    let num1 = 2;
    let num2 = num1 || 3;
    console.log(num2);  // 2  cause num1 is a truthy
    
    0 讨论(0)
  • 2020-12-07 17:13
    var x = y !== undefined ? y : 1;
    

    Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, ""), which may be why it "didn't work" for you. Also, if y is a global variable, if it's truly not defined you may run into an error unless you access it as window.y.


    As vol7ron suggests in the comments, you can also use typeof to avoid the need to refer to global vars as window.<name>:

    var x = typeof y != "undefined" ? y : 1;
    
    0 讨论(0)
  • 2020-12-07 17:13
    y = (y != undefined) ? y : x;
    

    The parenthesis are not necessary, I just add them because I think it's easier to read this way.

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