+ 22
What is the diffrence (in examples) between undefined, null, NaN ?
Difrences: Undefined Null NaN
10 odpowiedzi
+ 15
In general things are never null unless you manually set them to null, but many things are undefined by default.
Some interesting examples:
> typeof null
"object"
> typeof undefined
"undefined"
> typeof NaN
"number" // even though it's Not a Number :D
> NaN == NaN
false
> NaN != NaN
true
function foo() { }
> foo()
undefined
var foo;
> foo
undefined
> null == undefined
true
> null === undefined
false
> [].find(x => true);
undefined
> [].reduce(() => 0);
Uncaught TypeError
> 1/0
Infinity
> 0/0
NaN
> Number(null)
0
> Number(undefined)
NaN
+ 13
Undefined means that something has no definded value.
Null is the specific value to express nothing.
NaN means not a number an is the value that is returned from ilegal mathimatical expressions.
+ 10
Undefined mean when you didn't declare a variable but you call in this variable.
Null mean when you create a object or create string variable but you didn't inialize the value.
+ 8
Undefined = a variable was not defined
Null = a variable has nothing(0)
NaN = Not a Number
e.g: console.log('abc' * 3) will return a error NaN
+ 5
I'm not aware of anything that returns null, unless you do it yourself.
var foo = null;
> foo
null
function foo() { return null; }
> foo()
null
That means if you the want to explicitly communicate that some value is missing, you want to use null because so many things are undefined.
For example, if you have
var foo;
And you later use that variable and get an error because "something something undefined", that error can mean so many different things (typo, forgot to pass a parameter to a function, forgot to set a property of an object, and a hundred other things).
if you have
var foo = null;
and get an error because "something something null", you know that somehow somewhere you set that variable to null yourself. It helps a lot when debugging.
But all in all the differences are pretty minor.
+ 5
If on a prompt call the user clicks cancel, null is returned.
+ 4
Oof, why would they even do that.
+ 2
Give them a button, eventually they'll use it. ;)
+ 2
I wonder, what type of number is NaN
+ 2
To better understand "Undefined":
https://youtu.be/Bv_5Zv5c-Ts?t=2793