Search code examples
javascriptnode.jses6-modules

Meaning of 'this' in nodejs when using ES6 import/export


I have a javascript file

  1. When I am using es6 import/export and doing
console.log(this); // undefined

it is giving undefined.

  1. When I performed the same thing using require/module.exports
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.


Solution

  • 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.