• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

277
Vistas
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 3 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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 3 years ago · Santiago Trujillo Denunciar

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 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda