JavaScript - Difference Between Null And Undefined


// JavaScript - Differences between undefined and not defined:

In JavaScript, if you try to use a variable that doesn't exist and has not 
been declared, then JavaScript will throw an error var name is not defined and 
script will stop executing. However, if you use typeof undeclared_variable, 
then it will return undefined.  Let's say var x is a declaration because you 
have not defined what value it holds yet, but you have declared its existence 
and the need for memory allocation. If a variable that is neither declared nor 
defined, when we try to reference such a variable we'd get the result not 

// Difference between undefined, not defined, and null:
undefined is the value that is assign to a variable if we do not explicitly
initialize the variable with a value.  null is not assigned to a variable
unless that is what we explicitly do.  null is an object whereas undefined is
a value according to the typeof operator.

Undeclared variables are those that do not exist in a program and are not 
declared. If the program tries to read the value of an undeclared variable, 
then a ReferenceError is encountered.  Undefined variables are those that are 
declared in the program but have not been given any value. If the program 
tries to read the value of an undefined variable, an undefined value is returned.

undefined is not a constant or a keyword. undefined is a type with exactly 
one value: undefined.  Assigning a new value to it does not change the value 
of the type undefined.

null means empty or non-existent value which is used by programmers to indicate 
“no value”. null is a primitive value and you can assign null to any variable. 
null is not an object, it is a primitive value. For example, you cannot add 
properties to it. Sometimes people wrongly assume that it is an object, 
because typeof null returns "object".

console.log(null == undefined); // log true

// 8 Ways to get undefined:
1. A declared variable without assigning any value to it.
2. Implicit returns of functions due to missing return statements.
3. return statements that do not explicitly return anything.
4. Lookups of non-existent properties in an object.
5. Function parameters that have not passed.
6. Anything that has been set to the value of undefined.
7. Any expression in the form of void(expression)
8. The value of the global variable undefined
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License