0

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);

1 Answer 1

3
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();
Sign up to request clarification or add additional context in comments.

2 Comments

Gotcha, so would it be safe to assume that from this that "return index" is returning a value of 0 since function() isn't being called
The function certainly isn't being called, and that would prevent index from being incremented. You've got a couple of different indexes floating around, though, so if this doesn't fix your problem I'd make sure you're returning and incrementing the right one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.