Checking for missing parameter in function

前端 未结 4 1999
孤街浪徒
孤街浪徒 2021-02-01 16:57

Is this the correct way to check for a missing parameter in a function? Would this work in all browsers? How about IE?

function getName(name){
    name = name !=         


        
4条回答
  •  悲哀的现实
    2021-02-01 17:52

    you can do:

    name = name || 'default';
    

    That says if name is undefined or falsy (null, 0, "", false, {}, []), set it to "default".

    js(h|l)int will complain about it, but it works at least as far as back as IE7. It's not invalid code at all or relying on some undocumented behavior either.

提交回复
热议问题