Javascript: How to check if a string is empty?

JavascriptString

Javascript Problem Overview


I know this is really basic, but I am new to javascript and can't find an answer anywhere.

How can I check if a string is empty?

Javascript Solutions


Solution 1 - Javascript

I check length.

if (str.length == 0) {
}

Solution 2 - Javascript

If you want to know if it's an empty string use === instead of ==.

if(variable === "") {
}

This is because === will only return true if the values on both sides are of the same type, in this case a string.

for example: (false == "") will return true, and (false === "") will return false.

Solution 3 - Javascript

This should work:

if (variable === "") {

}

Solution 4 - Javascript

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

Solution 5 - Javascript

if (value == "") {
  // it is empty
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - JavascriptDustin LaineView Answer on Stackoverflow
Solution 2 - JavascriptnxtView Answer on Stackoverflow
Solution 3 - JavascriptTom CastleView Answer on Stackoverflow
Solution 4 - JavascriptChristopher RichaView Answer on Stackoverflow
Solution 5 - JavascriptRayView Answer on Stackoverflow