4

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?

Corey
  • 6,612
  • 4
  • 20
  • 28

2 Answers2

2

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

Federkun
  • 36,084
  • 8
  • 78
  • 90
1

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);
tanner burton
  • 1,049
  • 13
  • 14