Search code examples
javascriptiife

Why do I get undefined plus the value?


I'm very new to JS and I'm just playing around with syntax.

When I call

budgetController.publicTest2();

I get:

46 Undefined

I expected the 46 but why do I also get Undefined?

Full Code:

var budgetController = (function() {
    var x = 23;

    function add(a) {
        return a + x;
    }

    return {
        publicTest: function() {
            const y = add(23);
            return y;
        },
        publicTest2: function() {
            return (function(d){
                console.log(d());
            })(budgetController.publicTest);
        },
    }
    })();
    
budgetController.publicTest2();


Solution

  • Console prints out undefined because that is the return value of the budgetController.publicTest2() expression.

    Console always prints out the value of the expression that you entered. For example:

    • If you type in 1 + 2, you will get 3 back.
    • If you type in console.log(3) you will get back 3 and undefined (the return value of the expression console.log(3))