0

Say I have the following code.

function myFunc(item) {
    console.log(item);
}

function action() {
    return myFunc("Hello World");
}

const myUncalledFunction = action;
myUncalledFunction(); // will console.log "Hello World"

Is there a way to make this code cleaner? I've looked into .apply() but it looks like that calls the function immediately as well.

The reason I'm wanting to do this is Chai's expect for throw requires you to pass in an uncalled function. But the function I'm wanting to test requires arguments to be passed in. So currently I just created a wrapper function that returns the function with the arguments passed in.

I feel like there has to be a better way to achieve this that is cleaner and simpler for someone looking at it.

1 Answer 1

1

Use .bind to bind arguments (and a calling context, if needed) to a function, which produces a new callable function in the process. Here, you can see this as basically allowing you to pass in arguments at one time, and then call the desired function with those arguments later:

function myFunc(item) {
  console.log(item);
}
const myUncalledFunction = myFunc.bind(undefined, 'Hello World');
myUncalledFunction();

Or you might just use a concise arrow function

function myFunc(item) {
  console.log(item);
}
const myUncalledFunction = () => myFunc('Hello World');
myUncalledFunction();

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

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.