Search code examples
javascripttypescripthandlebars.js

handlebars / function ends up in impossible condition


I have the following handlebars helper, defined in a typescript file.

When the helper is fed the string "test", and maxResidualLength of 10, the debugger statement is hit, despite the inspector telling me that clippedString.length > maxResidualLength equals false

    Handlebars.registerHelper("ClipYearsFromString", function (strg: string, maxResidualLength:number) {
        var pattern = /(\b\d{4}.\b|\b\d{4}\b)/g; //remove sets of four digits or four digits with a non alpha character behind them.

        var clippedString = strg.replace(pattern, "");

        if (typeof (maxResidualLength) == "number" && maxResidualLength > 0) 
        {
            if (clippedString.length > maxResidualLength);
            {
                debugger;
                clippedString = clippedString.substr(0, maxResidualLength) + "…";
            }
        }
        return clippedString;
    });

The helper is being called in a template as follows :

   <span>{{{ClipYearsFromString SelectedRankingPool.PoolName 10}}}</span>

SelectedRankingPool.PoolName is always a string.

How is this happening? The same behavior occurs in all major browsers, be it Chrome, Firefox or IE , and it still happens if i take the helper registration outside of typescript and handlebars.

function derp(strg, maxResidualLength)
    {
      var pattern = /(\b\d{4}.\b|\b\d{4}\b)/g;   
      var clippedString = strg.replace(pattern, "");
      if (typeof (maxResidualLength) == "number" && maxResidualLength > 0) 
            {
                if (clippedString.length > maxResidualLength);
                {
                    debugger;
                    clippedString = clippedString.substr(0, maxResidualLength) + "&hellip;";
                }
            }
            return clippedString;
    }

    console.log(derp("test", 10)); //hits debugger


Solution

  • It's a nasty small thing. I see a ; in a weird place:

    if (clippedString.length > maxResidualLength); // <-- weird?
    

    Simple reproduction example:

    if(false); // ";" terminates the if statement.
    {
        alert('I get executed anyway...');
    }