646

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

Is there a less verbose way of checking that has the same effect?

According to some forums and literature saying simply the following should have the same effect.

if (some_variable)
{
    // Do something with some_variable
}

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tomas Vana
  • 18,317
  • 9
  • 53
  • 64
  • 63
    `if(some_variable) { ... }` will not execute if `some_variable` is `false` or `0` or ... – kennytm Apr 01 '10 at 09:22
  • 1
    good point ;) But let's say I know it can't be false or 0 and I just want to check whether I can use it in some logic (as a string, array, etc.) – Tomas Vana Apr 01 '10 at 09:24
  • Related: http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – Jørn Schou-Rode Apr 01 '10 at 09:58
  • 5
    ...or an empty string. – David Given Sep 16 '15 at 17:20
  • Possible duplicate of [How do you check for an empty string in JavaScript?](https://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – T.Todua Dec 04 '18 at 09:32
  • 2nd solution will be executed if `some_variable` is 0, False, or any other kind of falsy variable. This is very different from checking if something is `undefined` or `null` – Nicholas Hamilton Jun 18 '19 at 01:28

29 Answers29

633

I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

EDIT 2021-03:

Nowadays most browsers support the Nullish coalescing operator (??) and the Logical nullish assignment (??=), which allows a more concise way to assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

can be written as any of these forms

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
mar10
  • 14,320
  • 5
  • 39
  • 64
  • 1
    Very important difference (which was already mentioned in the question btw). That's why everyone uses typeof. Sorry but I don't get where your answer is useful, you just state what was said in the question and in the first few lines you state it even wrong. – Tomas Apr 19 '13 at 09:32
  • 44
    Sorry, but I have to disagree ;-) Using `== null` is imho the most efficient to test for 'null or undefined' (which is the questions topic). It is by no means uncommon (used 43 times in jQuery 1.9.1), since very often you know that the variable was declared - or you test for an property of an existing object like `if( o.foo == null)`. – mar10 Apr 19 '13 at 17:05
  • 5
    @mar10 (aUndefinedVar == null) gives you a "aUndefinedVar is not defined" error not true. – Rannnn Jul 29 '13 at 03:58
  • 1
    @Rannnn: this is discussed in 'Note 1' – mar10 Jul 29 '13 at 06:42
  • `==` behavior in Javascript is extremely confusing. You should spell out `v !== null && v !== undefined` to improve code readability, unless you are writing some very low level library code where the extra operation matters to performance (in which case you should test which version is faster, and my bet is still on with the longer one - type coercion is slow). – Tgr Mar 31 '15 at 08:50
  • 11
    Thanks for this succinct option. In 99% of my code there is no need to distinguish between null and undefined, therefore the brevity of this check results in less cluttered code. – Ian Lovejoy Apr 03 '16 at 19:19
  • 1
    To prevent a ReferenceError when checking a global variable, use `window.someProperty == null`. For local variables, you can easily make sure they are declared: instead of writing `if (...) {var local = ""}` write `var local; if (...) { local = ""; }` – Aloso Sep 18 '17 at 17:58
  • "Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null." I usually do == for boolean values too ("true" vs true). Thoughts? Is that bad practice? – dmathisen Oct 06 '17 at 17:16
  • @dmathisen I personally think so, yes. I'd use `if ( val )` to test for truthy or `if ( val === true ) ` for explicit tests. – mar10 Oct 07 '17 at 06:23
  • Wish Visual Studio's IntelliSense would like this (it complains when you further use the variable after this check that it could be null or undefined) – mhapps Mar 01 '18 at 09:45
  • I'm with @IanLovejoy. Almost always simplicity (not necessarily brevity) of code is more important than speed (who's doing compute intensive work in JavaScript?) This answer very explicitly answers the original question – Auspex Apr 24 '18 at 12:30
  • Hey wait!! I got an error when using `if ( some_variable == null )`, where some_variable is not defined. A simple example is here: https://jsfiddle.net/q20sx6o4/ . See error message in the console. Does this method really work for now? – Eric Oct 05 '18 at 11:54
  • @Eric this is discussed in „Note 1“ – mar10 Oct 07 '18 at 04:45
  • I cannot believe that the comments that recommend using `== null` are praised / upvoted so highly. This is a complete hack and you should NOT do this in production code. I asked around almost all our frontend devs and none of them knew (for certain) that only `undefined`/`null` pass this check. This kills readability and it smells of someone just wanting to prove they're especially smart. Any sane developer who reads this will get confused one way or the other, this is a very JS-specific quirk. TL;DR: Do Not Employ `== null` checks in your code if other people are going to use this code. – Danyel Jul 04 '19 at 20:24
  • 1
    @Danyel - the behavior is [in the spec](https://www.ecma-international.org/ecma-262/#sec-abstract-equality-comparison). And can easily be found by googling. If in doubt, a short comment `\\ null or undefined` on each usage would clarify for devs who lack this knowledge. I'd rather do that, than use a verbose equivalent every time. OTOH, if this might be an *undeclared* variable, to avoid an error it is unfortunately necessary to do `typeof(some_variable) !== "undefined" && ...`. – ToolmakerSteve Oct 26 '20 at 23:04
  • `x == null` is also true if `x` is an object with [`[[IsHTMLDDA]]`](https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot): `document.all == null`, but `document.all !== undefined && document.all !== null`. This may be desired behaviour. – Artyer Feb 28 '22 at 19:02
379

You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

A variable that has been declared but not initialized is undefined.

let foo;
if (foo) //evaluates to false because foo === undefined
  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue
    

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue
    
cutmancometh
  • 1,677
  • 3
  • 20
  • 28
user187291
  • 53,363
  • 19
  • 95
  • 127
  • 2
    Then you could talk about hasOwnProperty and prototypes. 'indexOf' in [] !== [].hasOwnProperty('indexOf') – Alsciende Apr 01 '10 at 09:58
  • 1
    Yes, i thought about adding this, but decided to sacrifice completeness for brevity. ;) – user187291 Apr 01 '10 at 10:06
  • 79
    you do not address the problem of 0 and false – Tomas Apr 11 '13 at 09:21
  • 13
    You mean *undeclared* variables. A variable can be declared but still have a value of `undefined`. – Tgr Mar 31 '15 at 08:42
  • 1
    And also note that `typeof` returns a string. So `var myVar; typeof(myVar)==undefined` returns `false` not `true`. – rism Nov 28 '15 at 07:57
  • @user187291 Why would `if(someUndefVar)` throw an error? is this outdated? – nramirez Jul 04 '17 at 14:48
  • 1
    `foo == null` (double equals intended) is my favorite check as it is falsey for `0` & `false` but truthy for both `undefined` & `null`. – IliasT Jul 28 '17 at 20:27
  • `obj.prop`: to only test a **property** for `null|undefined` (or property not declared), do `obj.prop == null`. This works because `undefined == null` is `true`, but other "falsy" values (`0` etc) are not: `0 == null` is `false`. Property tests do not result in reference error for missing property (assuming `obj` is an object). – ToolmakerSteve Nov 03 '20 at 21:19
88

Checking null with normal equality will also return true for undefined.

if (window.variable == null) alert('variable is null or undefined');

JS Equality

Semra
  • 2,787
  • 28
  • 26
  • 4
    NaN not equal to Nan? – Sharjeel Ahmed Mar 11 '16 at 12:49
  • 6
    @monotheist NaN is not equal to NaN (see [MDN's NaN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN)). Javascript uses IEEE-754 for their floating point which specifies this behaviors. There are some thoughts to this, see http://stackoverflow.com/a/23666623/2563765 – Steven Apr 13 '16 at 16:55
  • 1
    @SharjeelAhmed It is mathematically corrected. `NaN` from difference equation can never expected to be equal – Thaina Yu Oct 04 '19 at 04:12
55

This is the only case in which == and != should be used:

if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')

For any other comparisons, the strict comparators (=== and !==) should be used.

Yukulélé
  • 15,644
  • 10
  • 70
  • 94
33

In newer JavaScript standards like ES5 and ES6 you can just say

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say

if (Boolean(myvar)){
   // Do something
}

here "null" or "empty string" or "undefined" will be handled efficiently.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Naren Yellavula
  • 7,273
  • 2
  • 29
  • 23
  • 2
    supported down to like ie5, why is this not more well known!? – Himmators Jul 08 '16 at 13:00
  • 17
    OP just wanted test different of `null` and `undefined`, other falsy values should return true! – Andre Figueiredo Feb 19 '18 at 19:05
  • 2
    It adds no value in a conditional. The condition evaluates exactly the same and still returns false for `0`, `NaN`. This is for when you want to capture the truthiness of an object without keeping a reference to the object so you can store that rather than some potentially large object. FYI this is also equivalent to `!!value`, which the first `!` negates the truthiness, and the second negates it again. – Eric Haynes May 09 '18 at 22:30
  • *> FYI this is also equivalent to !!value, which the first ! negates the truthiness.* Which FYI is also equivalent to `if (var)` which will be cast to boolean, so basically completely useless... – Cyril CHAPON Jun 26 '18 at 09:42
  • 3
    While literally using the keyword _undefined_, `Boolean(undefined)` works, trying that with an undefined _variable_ **doesn't** work, and that is the whole point of doing the check for null or undefined. This: `if (Boolean(undeclareVarName)) { console.log('yes'); } else { console.log('no'); }` throws a ReferenceError saying "ReferenceError: undeclareVarName is not defined" – Stephen P Jul 12 '18 at 21:46
  • Boolean({}) returns true – Dmitry Stepanov Aug 04 '18 at 18:53
  • @DmitryS, Yes it returns true for empty list and object. But the question here asked is for null or undefined. – Naren Yellavula Aug 05 '18 at 08:25
  • 1
    @NarenYellavula - I disagree. The question asks for a solution *that is equivalent to* a code snippet they show, which tests for null or undefined. Your answer *is not equivalent to* that test. This propagates a bad habit that many JavaScript programmers have, and may confuse people just learning JavaScript. – ToolmakerSteve Oct 26 '20 at 23:10
28

If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:

if (window.some_variable != null) {
    // Do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 11
    You will miss NaN, 0, "" and false cause they are not null nor undefined but false as well. – Andreas Köberle Aug 30 '11 at 18:38
  • @Andreas Köberle is right. Even the non-strict equality operator says that null is different from NaN, 0, "", and false. You'd have to do `if (myObj.some_property != null)` to get equivalent behavior. – thejoshwolfe Apr 01 '13 at 05:53
18

Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.

A function, test(val) that tests for null or undefined should have the following characteristics:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

Let's see which of the ideas here actually pass our test.

These work:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

These do not work:

typeof(val) === 'undefined'
!!val

I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
11

here's another way using the Array includes() method:

[undefined, null].includes(value)
Jason Watmore
  • 4,521
  • 2
  • 32
  • 36
8

Since there is no single complete and correct answer, I will try to summarize:

In general, the expression:

if (typeof(variable) != "undefined" && variable != null)

cannot be simplified, because the variable might be undeclared so omitting the typeof(variable) != "undefined" would result in ReferenceError. But, you can simplify the expression according to the context:

If the variable is global, you can simplify to:

if (window.variable != null)

If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:

if (variable != null)

If it is object property, you don't have to worry about ReferenceError:

if (obj.property != null)
Tomas
  • 57,621
  • 49
  • 238
  • 373
  • Is `navigator` part of `window`? When we get an exception for `navigator is not defined`, can we use the `window.navigator != null` test? – jww Mar 02 '15 at 14:26
  • Re *`If it is local, you can probably avoid situations when this variable is undeclared,`*. Indeed, if it is *local*, it *cannot* be undeclared - so this is a non-problem. Your code snippet is always good. [If there is no *local* declaration of the variable, then it is - by definition - a reference to a *global* variable - which presumably is a programming mistake if you thought it was local, so having that result in a run-time error is a good thing. Reinforcing the value of using that shorter code snippet.] – ToolmakerSteve Oct 26 '20 at 23:24
5

This is an example of a very rare occasion where it is recommended to use == instead of ===. Expression somevar == null will return true for undefined and null, but false for everything else (an error if variable is undeclared).

Using the != will flip the result, as expected.

Modern editors will not warn for using == or != operator with null, as this is almost always the desired behavior.

Most common comparisions:

undeffinedVar == null     // true
obj.undefinedProp == null // true
null == null              // true
0 == null                 // false
'0' == null               // false
'' == null                // false

Try it yourself:

let undefinedVar;
console.table([
    { test : undefinedVar,     result: undefinedVar     == null },
    { test : {}.undefinedProp, result: {}.undefinedProp == null },
    { test : null,             result: null             == null },
    { test : false,            result: false            == null },
    { test : 0,                result: 0                == null },
    { test : '',               result: ''               == null },
    { test : '0',              result: '0'              == null },
]);
Sabo
  • 1,635
  • 1
  • 19
  • 24
4

You can just check if the variable has a value or not. Meaning,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}
DDave
  • 608
  • 6
  • 17
4

Similar to what you have, you could do something like

if (some_variable === undefined || some_variable === null) { do stuff }

gpap
  • 2,394
  • 2
  • 9
  • 8
  • Very obvious and easy to maintain code. Wish there was a specific operator for this (apart from '==') - something like '??some_variable' (akin to the Nullish coalescing operator, that groups 'null' and 'undefined' as falsy, but considers 0 as truthy). – Max Waterman Jun 30 '20 at 04:44
4

This is also a nice (but verbose) way of doing it:

if((someObject.someMember ?? null) === null) {
  // bladiebla
}

It's very clear what's happening and hard to misunderstand. And that can be VERY important! :-)

This uses the ?? operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator). If the value of someObject.someMember is null or undefined, the ?? operator kicks in and will make the value null.

TBH, I like the explicitness of this thing, but I usualle prefer someObject.someMember == null, it's more readable and skilled JS developers probably know what's going on here.

Elmer
  • 9,147
  • 2
  • 48
  • 38
  • 3
    This is not clear to me at all. I don't understand this syntax. Could you please explain? – Matt Jan 25 '22 at 23:31
  • @matt Its shorthand. It basically means if the value before the ?? is null or undefined, then default to the value after the ??. In this case, if someObject.someMember doesn't hold a value, then it will be assigned the value of null. And then we're checking the value is exactly equal to null. If it is, then we step inside the code block. – Ryan Tirrell Jun 26 '22 at 14:14
  • I independently thought of this solution, however yours has a bug: Due to the operator precedence it is actually equivalent to `if (someObject.someMember)`. You have to wrap the first part in parens like this: `if ((someObject.someMember ?? null) === null)`. You can test what I'm saying by running for example `false ?? null === null` in the console. Notice that it is `false` – Zachiah Oct 26 '22 at 20:15
  • You are right! Updated the example – Elmer Oct 28 '22 at 13:50
3

whatever yyy is undefined or null, it will return true

if (typeof yyy == 'undefined' || !yyy) {
    console.log('yes');
} else {
    console.log('no');
}

yes

if (!(typeof yyy == 'undefined' || !yyy)) {
    console.log('yes');
} else {
    console.log('no');
}

no

Terry Lin
  • 2,529
  • 22
  • 21
3

Open the Developer tools in your browser and just try the code shown in the below image.

Img1 Img2

Akash Preet
  • 4,695
  • 2
  • 14
  • 21
3

If the purpose of the if statement is to check for null or undefined values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator. According to the data from caniuse, it should be supported by around 85% of the browsers(as of January 2021). An example of the operator is shown below:

const a = some_variable ?? '';

This will ensure that the variable will be assigned to an empty string (or any other default value) if some_variable is null or undefined.

This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as 0 and ''.

wentjun
  • 40,384
  • 10
  • 95
  • 107
2

As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)

!!window['bleh'];

This would return a false while bleh has not been declared AND assigned a value.

Farax
  • 1,447
  • 3
  • 20
  • 37
  • However, it will *also* return false for any `falsey` value: the question asks for a test that *is equivalent to* `typeof(some_variable) != 'undefined' && some_variable != null`. This answer is not equivalent to that. – ToolmakerSteve Oct 26 '20 at 23:34
2

In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.

enter image description here

You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.

if (a === undefined || a === null || a==='') {
    console.log("Nothing");
} else {
    console.log("Something");
}

Also I want to point out one more thing.

What will be the result of Boolean(0)?

Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.

Dov Miller
  • 1,958
  • 5
  • 34
  • 46
Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79
2

With Ramda, you can simply do R.isNil(yourValue) Lodash and other helper libraries have the same function.

remjx
  • 4,104
  • 3
  • 34
  • 32
1

I have done this using this method

save the id in some variable

var someVariable = document.getElementById("someId");

then use if condition

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}
Mab Kiani
  • 576
  • 5
  • 16
1

In ES5 or ES6 if you need check it several times you cand do:

const excluded = [null, undefined, ''];

if (!exluded.includes(varToCheck) {
  // it will bee not null, not undefined and not void string
}
vladernn
  • 835
  • 1
  • 6
  • 7
1

let varToCheck = ""; //U have to define variable firstly ,or it throw error
const excluded = [null, undefined, ""];

if (!excluded.includes(varToCheck)) {
  // it will bee not null, not undefined and not void string
  console.log("pass");
} else {
  console.log("fail");
}

for example I copy vladernn's answer to test, u can just click button "Copy snippets to answer" to test too .

leonardosccd
  • 1,503
  • 11
  • 12
1

You can make use of lodash library.

_.isNil(value) gives true for both null and undefined

Test on - https://bazinga.tools/lodash

enter image description here

adityaatri
  • 1,967
  • 2
  • 7
  • 10
0

Testing nullity (if (value == null)) or non-nullity (if (value != null)) is less verbose than testing the definition status of a variable.

Moreover, testing if (value) (or if( obj.property)) to ensure the existence of your variable (or object property) fails if it is defined with a boolean false value. Caveat emptor :)

lucsorel
  • 33
  • 4
0

Best way to compare undefined or null or 0 with ES5 and ES6 standards

 if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
    // do something
    }
Faheel Khan
  • 556
  • 4
  • 4
0

you could use the following with nullish coalescing

//if statement evaluates to true only for null and undefined falsy values, false for others)

const val = ''; 

if(typeof val !== typeof(val ?? 1)) {
    console.log('Matches only null or undefined');
}else {
    console.log('Any other value');
}
Asanka Siriwardena
  • 871
  • 13
  • 18
0

You can check with this value is present or not.

if(value){
    // True Condition
}else{
// False Condition
}

Above code will evaluate to true if value is not:

  1. null
  2. undefined
  3. NaN
  4. empty string ("")
  5. 0
  6. false
Abijith Ajayan
  • 238
  • 3
  • 17
-1

You must define a function of this form:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ljofre
  • 314
  • 5
  • 18
-2

Both values can be easily distinguished by using the strict comparison operator.

Sample Code:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sohail Arif
  • 279
  • 2
  • 9