Search code examples
javascriptecmascript-6thisarrow-functions

this is Arrow functions in browser is global but not in NodeJS


in Google chrome

const ExampleObject5 = () => {
    console.log(this===window)
}

ExampleObject5()

Prints true

But in node

const ExampleObject5 = () => {
    console.log(this===global)
}

ExampleObject5()

Prints False


Solution

  • By reading NodeJS Documentation:

    global

    The global namespace object.

    In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside an Node.js module will be local to that module.

    So in Node the top-level scope is not the global scope (as in browser) but the module itself.