Is there any difference between:
foo is null
and foo == null
?
After we assign foo to null, it is still an “object” type, yet when we console.log the value of foo, it is simply “null”. In JavaScript, “undefined” is a global variable (a property of the global object), that is created at run time. This global variable represents something that has not been initialized.
Essentially in programming null means there is nothing there, and so if you attempt to do an operation on a null value your program will crash. The idea of null has been referenced as the billion dollar mistake (because null pointer exceptions cost companies a lot of money of money), you can read more about why null was a bad idea here.
Has NULL. Has an alternative in the language or standard libraries. Has NULL. Has an alternative in a community library. Has NULL. Programmer’s worst nightmare. Multiple NULLs. Don’t take the “ratings” too seriously. The real point is to summarize the state of NULL in various languages and show alternatives to NULL, not to rank languages generally.
But when something evaluates to “undefined”, it does not exist. In JavaScript, “null” and “undefined” have different meanings. While “null” is a special keyword that indicates an absence of value, “undefined” means “it does not exist”.
Short version: For well-behaved types, there is no difference between foo is null
and foo == null
.
Long version:
When you write foo == null
and an appropriate overload of operator ==
exists, then that's what is called. Otherwise, reference equality is used for reference types and value equality is used for value types.
When you write foo is null
for a reference type, this is compiled as if you wrote object.Equals(null, foo)
(notice the switched order, it makes a difference). In effect, this performs reference equality comparison between foo
and null
. For a value type, foo is null
does not compile.
This means that if you write a class with operator ==
that says that some instance of foo
is equal to null
, then foo == null
will give different result than foo is null
.
An example showing this:
using System;
public class Foo
{
public static void Main()
{
var foo = new Foo();
Console.WriteLine(foo == null);
Console.WriteLine(foo is null);
}
public static bool operator ==(Foo foo1, Foo foo2) => true;
// operator != has to exist to appease the compiler
public static bool operator !=(Foo foo1, Foo foo2) => false;
}
This code outputs:
True
False
When you overload operator ==
, you should make it behave in a reasonable way, which, among other things, means you should not say that foo == null
is true
for non-null
foo
. As a side effect of this, under normal circumstances, foo == null
and foo is null
will have the same value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With