Search code examples
javascriptclosuresundefinedreferenceerror

javaScript closures. Undefined value as input stops script. Sometimes


Playing with javascript closures I end up with this question I cannot reach to explain.

(function() {
    console.log("Inside closure"); //does not work
}(foo));

It does not work because foo is undefined. referenceError

But if prior I set var foo = undefined; it works (tested on Chrome and ff).

It is not the same to be undefined that to be set to undefined?

example in jsfiddle


Solution

  • In javaScript, 'undefined' is one of the primitive data types. It represents the type of an object.

    var a = undefined;
    var b;
    
    console.log((typeof(a)));
    console.log((typeOf(b)));
    

    The output will be undefined for both the cases.

    If you don't declare a variable at all and try to access it, the error thrown will be the following. I tried to access c which is not declared at all. Uncaught ReferenceError: c is not defined(…)