JavaScript Function declaration cautions!

Just found Kontagent‘s JavaScript library has a issue. When you declare functions in JavaScript as so below, the behavior isn’t as expected!

a = 5;

if (a == 5)
{
    function yo()
    {
        alert("good");
    }
}
else if (a == 6)
{
    function yo()
    {
        alert("bad");
    }
}

yo();

Be sure to declare your dynamic functions like so:

a = 5;
var yo;
if (a == 5)
{
    yo = function()
    {
        alert("good");
    }
}
else if (a == 6)
{
    yo = function()
    {
        alert("bad");
    }
}
yo();

As in Actionscript (also ECMAScript based), declaring functions the first way will be global scope. And the last function defined will be the one that is used.

We were trying to debug why Kontagent‘s library wasn’t pinging the right events (in our case Invite Sent notifications). When we investigated the code we saw they wrapped function calls inside ifs as above… Hopefully they will read this blog post and implement a fix as suggested :-).
So be careful developers!

*Edit: We sent a Pull request to their github with our fix

4 thoughts on “JavaScript Function declaration cautions!”

Leave a Reply

Your email address will not be published. Required fields are marked *