Undefined In JavaScript

Undefined is a confusing type in JavaScript, but first I will start with the obvious cases. Like the null type can only be null, the undefined type can only be undefined. Firstly there is a global undefined variable with the value of undefined:

console.log(typeof undefined);// "undefined"

When a variable is not defined, it is undefined:

var x;
console.log(x);// undefined

When it doesn’t exist, using it will cause an error. Instead its type can be checked for undefined:

console.log(typeof notStated === 'undefined');

All functions with no explicit returns return undefined:

var function1 = function() {};
console.log(function1());// undefined

var function2 = function() {
console.log(function2());// undefined

Unlike null, undefined is supposed to represent when something has not been assigned a value. What makes it confusing is that just like null, variables and properties can be given an undefined value. Meaning there could be variables and properties with an undefined value that have been defined. So there is no way to differentiate between a declared but unassigned variable and a non existent one without catching an error:

var x;
console.log(typeof x);// undefined
console.log(typeof y);// undefined
x = undefined;
console.log(typeof x);// undefined

try {
} catch (e) {
    if ((e + '').indexOf('ReferenceError') > -1) {
        console.log(e.message);// notStated is not defined: 

Object properties when not assigned are undefined:

var obj = {};
console.log(obj.property1);// undefined

// Remember that array positions are properties too
var arr = [1, 2, 3];

console.log(arr[3]);// undefined
console.log(arr['3']);// undefined

Since properties can also be given the undefined value a different type of check needs to be made:

console.log(obj.hasOwnProperty('property1'));// false
// For checking inherited properties
console.log('property1' in obj);// false
console.log('toString' in obj);// true

Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2015/undefined.js