How can I check for an empty/undefined/null string in JavaScript?

后端 未结 30 4126
长发绾君心
长发绾君心 2020-11-21 23:47

I saw this question, but I didn\'t see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking f

30条回答
  •  后悔当初
    2020-11-22 00:01

    Starting with:

    return (!value || value == undefined || value == "" || value.length == 0);
    

    Looking at the last condition, if value == "", its length must be 0. Therefore drop it:

    return (!value || value == undefined || value == "");
    

    But wait! In JavaScript, an empty string is false. Therefore, drop value == "":

    return (!value || value == undefined);
    

    And !undefined is true, so that check isn't needed. So we have:

    return (!value);
    

    And we don't need parentheses:

    return !value
    

提交回复
热议问题