Shorthand if/else statement Javascript

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

提交回复
热议问题