32

I always (thing != undefined || thing != null)?...:...; check. Is there any method will return bool after this check in javascript or jquery ?

And how would you add this check in jquery as a function?

4 Answers 4

46
if (thing)
{
   //your code
}

Is that what you are looking for?

Sign up to request clarification or add additional context in comments.

6 Comments

:) this is really very easy isn't it :D
Be careful - this string and maybe a few others will fail that check: "0".
He didnt ask for "0" and "false", but undefined or null.
@Joel: Wrong. All non-empty strings are truthy.
@SLaks But only when no comparison is involved, so if("0") will be true but if("0" == true) won't, since type conversion took place.
|
25

In Javascript, the values null, undefined, "", 0, NaN, and false are all "falsy" and will fail a conditional.
All other values are "truthy" and will pass a conditional.

Therefore, you can simply write thing ? ... : ....

Comments

1

Try this

  function SringisEmpty(str) {
        str=str.trim();
        return (!str || 0 === str.length);
    }

Comments

0

As the others here have mentioned, several things evaluate as "falsy" that you might not want to (such as empty strings or zero). The simplest way I've found in JavaScript to check for both null and undefined in one statement is:

thing != null

This is using type coercion (double equals instead of triple equals), so undefined values are coerced to null here, while empty strings, zero, etc. do not.

Comments

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.