javascriptnamespaces

JavaScript NameSpace already declared error


I am loading a script with the jQuery getScript function after the document is ready. The script has these 2 lines:

const myNameSpace={};

function myNameSpace.test() {
}

I am getting this error:

error message

I have used NameSpaces elsewhere in the project in the same way and did not get this error.


Solution

  • You can't use a property name in a function declaration. The parameter has to be a single identifier.

    You can write

    myNameSpace.test = function() { };
    

    or put the function definition directly in the object literal

    const myNameSpace = {
        test() { }
    }