When writing a function that returns some kind of result, if nothing is returned then the default value that is returned is undefined. To have a function return something other than undefined the return keyword can be used inside the body of a function to define what it is that is to be returned.
When writing a function that accepts one or more arguments if an argument is not given then the default value for the argument is undefined. So testing for undefined is often used as a way to determine of no argument is given,and then thus set a default for that argument when writing a function.
So then there are two general ways to avoid this, if you are going to use expressions just make sure that they are set to the variable that you are calling them off first before calling them. The other way to avoid this is to not use function expressions, but function declarations in place of expressions.
One of the weird things about the isNaN method is that it will return true for some values that are not NaN including the undefined value. Because of this there are often isNaN methods in various frameworks besides the fact that there is a native method for doing so that do a better job of finding out if a value is nan or not.
There is also the undefined keyword or literal as it might sometimes be called. This is often used as a way to test for undefined.I can not say that there are many instances in which I set a variable or property to undefined, or pass undefined as an argument, but it can also be used that way as well. Still for the most part I find myself using it in expressions to test for the undefined.
It would seem that some developers at stack overflow like to use the typeof operator in expressions that test for undefined as it will not throw an error in the event that a variable is not declared.
However if a variable is not undefined that would imply that a variable is defined, but that it not the case. The variable is not even declared, let alone defined.
So then in a way there are three possible states, a variable is not even declared, a variable is declared but undefined, and a variable is declared and is a value other than undefined.
In this above example the value of r can be zero which is the default and will remain so if the variable myVar is both declared and defined. It will have a value of one if the variable is declared but undefined, and a value of negative one if it is undeclared.
When using the equality operator a value of true is the result. This is because the equality operator converts types to a common type and then compares the result. Both the null and undefined values convert to false, and false equals false, so the result is a true value.
However when the identity operator is used to make a comparison a false value is the result. This is because when the identity value is used type conversion does not occur. The null and undefined values are two different types, so the result is false.