Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

356
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!