0

I am returning an array from a function in JavaScript and I need to be able to know when it contains nothing but a single empty string. When I print that value to the console, it returns this:

[""]

I get an error if I do the following:

if(myVar == [""]){
    // do something
}

How can I test for that value in that variable? jQuery answers are perfectly acceptable as well as plain JavaScript.

1
  • 1
    You should not get an error when doing myVar == [""]. What's the error? Commented Oct 13, 2014 at 18:06

2 Answers 2

4

I would use:

if( myVar instanceof Array && myVar.length === 1 && myVar[0] === '' ) {
// ....
}
Sign up to request clarification or add additional context in comments.

1 Comment

typeof myVar will return "object", so this won't work. Use myVar instanceof Array instead ;)
1
if (myVar.length == 1 && myVar[0] == ""){   
}

3 Comments

What if myVar is ['',1,2,3]
Edited, now it works if the array only contains strings.
You should change == to ===.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.