Shorthand if/else statement Javascript

前端 未结 7 1427
难免孤独
难免孤独 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: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
    

提交回复
热议问题