[removed] use either a variable, or if it's undefined, a default string

后端 未结 7 975
太阳男子
太阳男子 2020-12-10 00:49

I have this code:

var phrase = function (variable, defaultPhrase) {
    if (typeof variable === \"undefined\") {
        return defaultPhrase;
    }
    else         


        
7条回答
  •  青春惊慌失措
    2020-12-10 01:15

    In javascript, you typically use the OR operator || to provide an alternative value when a variable is undefined:

    return variable || defaultPhrase || ''
    

    In case variable is undefined, it will evaluate to false then the second part of the test will be evaluated, if it is also undefined, you can still return an empty string.

提交回复
热议问题