Zayn Ali Zayn Ali - 4 months ago 14
Node.js Question

Module Pattern Error in ES6 (Augmentation)

I'm getting an error while using module pattern (Augmentation) with ES6 let keyword.

This works.

var Example = ( Example => {
Example.name = "";
return Example;
})( Example || {} );

console.log(Example);


This does not.

let Example = ( Example => {
Example.name = "";
return Example;
})( Example || {} );

console.log(Example);


I'm getting this error.


Uncaught ReferenceError: Example is not defined


})( Example || {} );
^^^^^^^

Answer

The answer becomes fairly clear when you realize that this:

var x = (j => j)(x)

..becomes this:

var x = undefined
x = (j => j)(x)

It really declares x as undefined before evaluating the expression and setting x to the result.

However, let doesn't have that property - it's not hoisted:

let y = (j => j)(y)

..gets evaluated as just that.

y doesn't exist when you do (j => j)(y), so it throws a reference error.