0

script1.js

let log = "log";

function a() {
  console.log(log);
}

export { a };

script2.js

import { a } from "./script1.js";

a(); // log
console.log(log) // Uncaught ReferenceError: log is not defined

Why does this work? Why does the function know what log is even though log is not defined?

Fusscreme
  • 152
  • 9
  • 1
    Most of the time, your modules will import other modules, and you will define functions which use those imported modules, and you will export those functions and use them in other modules… you’d expect that to work without having to import the dependencies of your dependencies of your dependencies, right? – deceze Mar 02 '23 at 19:32
  • That's a good way to think about it, thanks. I always knew it works, but I never knew why and this confused me. Thanks for referrring me to closures, I'll look it up. – Fusscreme Mar 02 '23 at 19:43

0 Answers0