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

后端 未结 30 4597
长发绾君心
长发绾君心 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-21 23:58

    I didn't see a good answer here (at least not an answer that fits for me)

    So I decided to answer myself:

    value === undefined || value === null || value === "";

    You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.

    You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false).

    With that said, wrap it up in a method like:

    public static isEmpty(value: any): boolean { return value === undefined || value === null || value === ""; }

    PS.: You don't need to check typeof, since it would explode and throw even before it enters the method

提交回复
热议问题