Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function becomes undefined when returned

I have:

  • a dictionary (functions) mapping string prefixes to functions
  • a function (get()) that returns the function mapped to a string
  • a function (check()) that checks if there's a function mapped to a string by calling get() and casting it to a boolean with !!.

When I call get() with a key in functions, I expect that check() returns true; however, it returns false. I perform the dictionary lookup in get() and print the type of the result in both functions. Here's the weird part. The type is function only in get(); in check(), it's undefined. Apparently, the function gets erased or something when I return it. How can I make check() accurate?

Here's my simplified code:

var someObject = {
    functions: {
        "a": function () { return 0; },
        "b": function () { return 1; }
    },
    get: ( function ( someVariable ) {
        Object.keys( this.functions ).forEach( ( function ( functionKey ) {
            if ( someVariable.startsWith( functionKey ) ) {
                console.log( typeof this.functions[ functionKey ] );
                return this.functions[ functionKey];
            }
        } ).bind( this ) );
    } ),
    check: function ( stringToCheck ) {
        var returnedFunction = this.get( stringToCheck );
        console.log( typeof returnedFunction );
        return !!returnedFunction;
    }
}

$( document ).ready( function () {
    someObject.check( "a" );
} );

Running this code produces this:

"function"
"undefined"

in the console.

like image 943
APerson Avatar asked Dec 12 '25 19:12

APerson


1 Answers

It's because forEach does not break early/short circuit on the return statement (it continues with the next iteration, and then the get function returns undefined). You could re-write the loop to allow breaking (say, with a simple for-loop), or you could return the value after looping, such as:

var someObject = {
    functions: {
        "a": function () { return 0; },
        "b": function () { return 1; }
    },
    get: ( function ( someVariable ) {
        var func;
        Object.keys( this.functions ).forEach( ( function ( functionKey ) {
            if ( someVariable.startsWith( functionKey ) ) {
                console.log( typeof this.functions[ functionKey ] );
                func = this.functions[ functionKey];
            }
        } ).bind( this ) );
        return func;
    } ),
    check: function ( stringToCheck ) {
        var returnedFunction = this.get( stringToCheck );
        console.log( typeof returnedFunction );
        return !!returnedFunction;
    }
}
like image 163
Jack Avatar answered Dec 14 '25 10:12

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!