Oliver Williams Oliver Williams - 6 months ago 9
Javascript Question

javascript - what is the purpose of declaring a variable a function first?

Here is the code I have encountered:

var c = function() {},
c = {
autoSelectFirst: !1,
appendTo: "body",
serviceUrl: null,
lookup: null,
.. etc..
lookupFilter: function(a, b, c) {
return -1 !== a.value.toLowerCase().indexOf(c)
},
.. etc..
};


Why is
c
first declared as an empty function then re-declared as an object? Doesn't that just overwrite the function declaration? I suppose it is a fundamental JS construct.

Answer

Based on this code example from the original question:

var c = function() {},
    c = {
        autoSelectFirst: !1,
        appendTo: "body",
        serviceUrl: null,
        lookup: null,
        .. etc..
        lookupFilter: function(a, b, c) {
            return -1 !== a.value.toLowerCase().indexOf(c)
        },
        .. etc..
    };

The c = function() {}, part in the code that is included in your question has no point. It's like doing:

var x = 1, x = 3;

There's no point in assigning one value to the variable and then immediately assigning another value to it.

The code you show would generate the exact same result (with less confusion) as this:

    var c = {
        autoSelectFirst: !1,
        appendTo: "body",
        serviceUrl: null,
        lookup: null,
        .. etc..
        lookupFilter: function(a, b, c) {
            return -1 !== a.value.toLowerCase().indexOf(c)
        },
        .. etc..
    };

Based on the comments for where this code was found, it appears that it is part of some automatic code generation or minimization process.

FYI, Javascript does not use the phrase "associative array". The second declaration is a Javascript object.

Comments