1

I have the following code. It runs a simple function and the same function needs to run. (Recursive)

var Skit = function(callback) {
    validSkit(Math.random(),function(skit,data){
        // Ajax callback
        if (skit == true) callback(data); // Works if skit is found
        else if (skit == false) Skit(callback); // Call Skit again [not working]
    });
}(function(skit){
    console.log("Valid skit found!");
});

I'm getting Skit is undefined! I know I could do this true simple function Skit().. call. But this is not my requirements. Is this possible?

3
  • 1
    Try var Skit = function Skit(callback). Commented May 12, 2015 at 14:46
  • or rather (function Skit(callback){... This would be a classical named function expression. Commented May 12, 2015 at 14:46
  • The function expression is immediately invoked, and the function has no return value, hence the value of 'Skit' is undefined. What is it that you want this code to do though? Commented May 12, 2015 at 14:52

2 Answers 2

2

You should use a named function expression here:

(function Skit(callback) {
    validSkit(Math.random(),function(skit,data){
        // Ajax callback
        if (skit == true) callback(data); // Works if skit is found
        else if (skit == false) Skit(callback); // Call Skit again [not working]
    });
})(function(skit){
    console.log("Valid skit found!");
});

Note that the Skit name won't leak in the outside scope and it will be available for debug in the stack traces.

Sign up to request clarification or add additional context in comments.

Comments

0

In this case var Skit variable is the returned value.

(function (callback) {
...
})(function () {console.log('I am argument function')}); 

If you returned smth from it (after validSkit execution, for exampe, or before, whatever) then the value of Skit would be return value. As far as return statement is absent, it returns undefined by default.

So you need firstly to initiate function without calling it and then call it by its name:

 var Skit = function(callback) {
    validSkit(Math.random(),function(skit,data){
        // Ajax callback
        if (skit == true) callback(data); // Works if skit is found
        else if (skit == false) Skit(callback); // Call Skit again [not working]
    });
};

Skit(function(skit){
    console.log("Valid skit found!");
});

Comments

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.