Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a risk of namespace collision of two constants, if used in imported modules but declared outside of them?

Tags:

javascript

If I have three files, basically something like this:

file_one.js:

const lol = () => {
    console.log('Laughing out loud in file_one')
}

const funcOne = () => {
    lol()
}

export default funcOne

file_two.js:

const lol = () => {
    console.log('Laughing out loud in file_two')
}

const funcTwo = () => {
    lol()
}

export default funcTwo

one_and_two_importer.js:

import funcOne from 'file_one'
import funcTwo from 'file_two'


funcOne()
funcTwo()

My assumption was that the function lol would be in global scope and thus cause a namespace collision, but apparently that doesn't happen. Also, if I try to log the function lol in one_and_two_importer.js, I get undefined error.

As the documentation says, import inserts the module to the current scope, but in which scope are the constants that are used by the imported modules?

like image 585
Jaakko Karhu Avatar asked Oct 29 '22 10:10

Jaakko Karhu


1 Answers

The two lol functions are now closures, which means that although they still get called inside each of the funcOne and funcTwo functions, they are hidden in the sense that they are not publicly accessible.

With ES6 modules (or commonJS for that matter), the only names that get injected into the local namespace are the names that you explicitly import, eg in all the cases

import x from 'y'
import { x } from 'y'
import * as x from 'y'

The namespace will only get the additional variable of x. No other variables get injected in a hidden manner.

The only way that you would get a clash is if you were to export the lol variable explicitly in both files and then try to import it by its name. Eg having in both files

export lol

and then

import { lol } from 'file_one'
import { lol } from 'file_two'

Unless you try to do something like this, the two lol variables would be scoped to their respective modules and so wouldn't conflict with each other.

I'd recommend reading more about how closures work in JavaScript.

like image 128
Aron Avatar answered Nov 15 '22 01:11

Aron