cmeitester
cmeitester

Reputation: 41

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.

Upvotes: 4

Views: 3213

Answers (1)

lAbYriNth
lAbYriNth

Reputation: 81

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!

Upvotes: 2

Related Questions