0

I want to create variable which contains a function with variable input.

I tried this but no success


var setup = function( isAjaxSuccess ) {
    return function( ajaxSuccess = isAjaxSuccess ){

       if( ajaxSuccess === true ){
           console.log("success");
       } else {
           console.log("error");
       }        

    };

};

Here we call setup( true ) or setup( false ) according to which function changes. Here console.log is just for show. Here setup( true ) should return a function basically.

5
  • 1
    Where is data being provided? Commented Jun 27, 2019 at 3:33
  • 1
    What is the error you are getting? There's a lot of things which can go wrong. The variable syntax seems to be correct Commented Jun 27, 2019 at 3:34
  • can take data as console.log("success"); Commented Jun 27, 2019 at 3:34
  • syntax error @Samuel Commented Jun 27, 2019 at 3:35
  • Line? Where is the Syntax error? That's still too broad. Commented Jun 27, 2019 at 3:36

3 Answers 3

2

Just return a function that uses ajaxSuccess:

var setup = function(ajaxSuccess) {
  return function() {
    if (ajaxSuccess === true) {
      console.log('success');
    } else {
      console.log('fail');
     }
  }
};

setup(true)();
setup(false)();

You could also make it more concise like so:

const setup = ajaxSuccess => () => ajaxSuccess ? console.log("success") : console.log("fail");
setup(true)();
setup(false)();

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

Comments

0

You don't need to run the return statement; just check the input inside the conditional:

var setup = function(ajaxSuccess) {
  if (ajaxSuccess === true) {
    console.log('success');
  } else {
    console.log('fail');
  }

};

setup(true);
setup(false);

1 Comment

Here setup(true) will not return a function which is what i want for my usecase
0

Because calling setup(true) returns a function, you will need to, in turn, call that function. Try:

var setup = function(isAjaxSuccess) {
    return function() {
        if (isAjaxSuccess === true ) {
            console.log("success");
        } else {
            console.log("error");
        }
    };
};

var result = setup(true);
result(); // will log "success" to the console

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.