Snorlax
Snorlax

Reputation: 4735

Javascript Function not executing/returning value

I have a function and I want to see what the value of index is. It gives me 0 however. I thought that was wierd so I put a console.log in function() to see if it was executing or not and I didn't recieve an output which tells me that function() isn't getting called. Not sure what I'm doing wrong.

function jsTest() {

    var index = 0;
    var counter = 0;
    var obj = {};
    obj.index = index; //obj.index = 0 at this point

    var func = function () {

        for (index = 0; index < 10; index++) {
            counter += 2;
            console.log(counter); //Doesn't execute for some reason
        }
        obj.index++;
    };

    obj.func = func; //executes function()
    this.index++;
    return index;
}

var x = jsTest();
console.log(x);

Upvotes: 0

Views: 47

Answers (1)

StephenTG
StephenTG

Reputation: 2647

obj.func = func;

doesn't actually call func, it assigns the property func for obj to be the function func. If you want to call func, you should add parentheses afterwards, like

obj.func = func();

Upvotes: 3

Related Questions