Corey
Corey

Reputation: 6822

Assignment to an undeclared variable throws ReferenceError in Node only when using ECMAScript modules

I have the a file index.js with these contents:

const test = function (cb) { cb(); };
test(myCallback = function () { console.log('done'); });

When I run index.js using Node v16.6.1 and CommonJS:

done

When I run index.js using Node v16.6.1 with "type": "module" in my package.json file:

ReferenceError: myCallback is not defined

Can you tell me whether and how this relates to ECMAScript modules?

Upvotes: 4

Views: 523

Answers (2)

tanner burton
tanner burton

Reputation: 1159

There are two ways to name functions. You can set a variable equal to a function. Or you can give a function a name. Here are two ways to solve your problem

Name the function

test(function myCallback () { console.log('done'); });

Set variable equal to function

const myCallback = function () { console.log('done'); }
test(myCallback);

Upvotes: 1

Federkun
Federkun

Reputation: 36924

This is a side effect from using ESM. Strict mode (use strict) is enable by default. Which cause the error, because: myCallback isn't declared anywhere.

let myCallback;
test(myCallback = function () { console.log('done'); }); // here we assign myCallback to a function. are you sure you want to actually do this?

Before, you were attempting to create a global variable.

First, strict mode makes it impossible to accidentally create global variables. [...] Assignments, which would accidentally create global variables, instead throw an error in strict mode

Upvotes: 2

Related Questions