javascript check for not null

javascript check for not null

this will do the trick for you

if (!!val) {
    alert(this is not null)
} else {
    alert(this is null)
}

There are 3 ways to check for not null. My recommendation is to use the Strict Not Version.

1. Strict Not Version

if (val !== null) { ... }

The Strict Not Version uses the Strict Equality Comparison Algorithm http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6. The !== has faster performance, than the != operator because the Strict Equality Comparison Algorithm doesnt typecast values.

2. Non-strict Not Version

if (val != null) { ... }

The Non-strict version uses the Abstract Equality Comparison Algorithm http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3. The != has slower performance, than the !== operator because the Abstract Equality Comparison Algorithm typecasts values.

3. Double Not Version

if (!!val) { ... }

The Double Not Version !! has faster performance, than both the Strict Not Version !== and the Non-Strict Not Version != (https://jsperf.com/tfm-not-null/6). However, it will typecast Falsey values like undefined and NaN into False (http://www.ecma-international.org/ecma-262/5.1/#sec-9.2) which may lead to unexpected results, and it has worse readability because null isnt explicitly stated.

javascript check for not null

Its because val is not null, but contains null as a string.

Try to check with null

if (null != val)

For an explanation of when and why this works, see the details below.

Leave a Reply

Your email address will not be published.