I have a javascript file
console.log(this); // undefined
it is giving undefined.
console.log(this); // {}
it is giving an empty module.exports object.
My question is - Why it is giving undefined in the case of es6 import/export.
In an ES6 module (using export
and import
declarations), the this
keyword defaults to the value undefined
- there is no reasonable object it should refer to. This also makes us recognise a lot more mistakes, where you accidentally refer to the this
of the module (e.g. writing an arrow function in an object literal) but meant to have dynamic this
or something else - the code breaks upon accessing a property on undefined
, instead of accessing a property on some other object.
If you want to reference the global object from a module, explicitly use globalThis
instead.
In a CommonJS module (using module.exports
and require()
), it refers to the module object - see What does "this" mean in a nodejs module? or Meaning of "this" in node.js modules and functions.