Search code examples
javascriptnamed-scope

Javascript variables conflict in different files


I have declared two variables with the same name using the const keyword in two different javascript files. But still I get an error when I import both the files together to a web page.

I know that var declares global scope variables which would conflict but I had heard that const and let do not bahave like that.

How do I fix this.


Solution

  • If you're just looking for an easy solution, having code blocks in the files will work, either as a self executing function or just a plain block:

    // On both files
    (function(){
        const x = 123;
    })();
    
    // or just a code block
    {
        const x = 456;
    }
    

    However, this is usually fixed by using a preprocessing tool like webpack (and organizing your code into modules to keep things separate), or at least having different classes and functions.