0 votes
in JavaScript by
What's the output?
// index.js
console.log('running index.js');
import { sum } from './sum.js';
console.log(sum(1, 2));

// sum.js
console.log('running sum.js');
export const sum = (a, b) => a + b;
  • A: running index.jsrunning sum.js3
  • B: running sum.jsrunning index.js3
  • C: running sum.js3running index.js
  • D: running index.jsundefinedrunning sum.js

1 Answer

0 votes
by

Answer: B

With the import keyword, all imported modules are pre-parsed. This means that the imported modules get run first, the code in the file which imports the module gets executed after.

This is a difference between require() in CommonJS and import! With require(), you can load dependencies on demand while the code is being run. If we would have used require instead of importrunning index.jsrunning sum.js3 would have been logged to the console.

...