Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does import really work in Javascript

I am having trouble understanding how import works in Javascript. Is it not supposed to just import the named function.

Here are my 2 files -

test.js -

export const add = (a,b) => {
    return a+b
}

export const subtract = (a,b) => {
    return a-b
}

console.log(add(7,7))

console.log(subtract(6,7))

and index.js

import { add } from './test.js'

console.log(add(4,5));

When running node index.js here is the output

14

-1

9

Why is the import also running the function calls in test.js

Thanks for your help.

like image 986
cmeitester Avatar asked Oct 15 '25 16:10

cmeitester


1 Answers

In js import works in a way that the imported modules are invoked first wherever you place your import statements in your file and after that your current file is executed. That's how js works!

like image 55
lAbYriNth Avatar answered Oct 17 '25 05:10

lAbYriNth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!