Home  >  Q&A  >  body text

Default parameter problem

Teacher, in the example you gave:

function func2(param1, param2) {

param1 = arguments[0] ? param1 : 600;

param2 = arguments[1] ? param1 : 300;

}

This ternary operator, if I call it like this: func(0, 0,);

I pass in If the parameter is 0, it will actually be judged as failure, and param1 and param2 will be assigned values ​​of 600 and 300

西伯利亚狼西伯利亚狼1220 days ago896

reply all(2)I'll reply

  • 猪老湿

    猪老湿2021-06-21 09:49:27

    It is inappropriate to set default parameter values ​​in this way. In fact, js now supports default parameters, so there is no need for such trouble (es6)

    reply
    0
  • 西伯利亚狼

    Teacher, what I mean is how to solve the problem of incorrect judgment of 0 and null by the ternary operator. When I was using objects, I encountered a link judgment: obj?.user?.first name?? undefined Not sure if this method can be applied to the above example!

    西伯利亚狼 · 2021-06-21 10:44:47
  • Cancelreply