Typically, when we try to access
something that doesn't exist.Or
variable with no value assigned, you will get a
undefinedValue. JavaScript automatically sets the variable that is declared to be not initialized to undifined.
What happens if a variable doesn't exist at all:
>>> Fooreferenceerror:
foo is not defined
We got an error message. We use the typeof operator on this variable to see what type it is:
>>> typeof Foo
"undefined"
The result we get is the string "undefined".
If we do not assign a variable when we declare it, the variable is called without error, but the typeof operator still returns the string "undefined".
>>> var somevar;>>> somevar;undefined>>> typeof Somevar; "
undefined"
And the null value is completely different. He cannot come from a dynamic assignment through JavaScript, which means that we have to manually assign a value to NULL for a variable:
>>> var somevar = null;>>> Somevar;
NULL
Moreover, the TypeOf operator returns an Object!
>>> typeof Somevar; "
Object"
Although the difference between undefine and Null is not very large, they behave very differently in some arithmetic operations:
>>> var i = 1 + undefined; I
NaN>>> var i = 1 + null; I
1
This is because the method has some difference when undefined and null are converted to other basic types, and we give some possible types of conversions below.
Convert to a number (treat undefined as a string, null as 0):
>>> 1 * undefined; Nan>>> 1 * null;0
Convert to a Boolean value:
>>>!! Undefined;false>>>!! Null;false converted to a string (all corresponding to a string):>>> "+undefined;" Undefined ">>>" +null; Null
The above is the difference between undefined and null, and where operations are to be noted.
The difference between undefined and null in JavaScript