Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

80
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?

8 months 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

8 months 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);
8 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.