Sometimes, we want to wrap a function with JavaScript.
In this article, we’ll look at how to wrap a function with JavaScript.
Wrap a Function with JavaScript
To wrap a function with JavaScript, we can return a function inside a function.
For instance, we write:
const wrap = (someFunction) => {
const wrappedFunction = (...args) => {
const newArgs = [...args, 'another argument']
return someFunction(...newArgs)
}
return wrappedFunction
}
const doThing = (...args) => {
console.log('do thing', args)
}
const wrappedDoThing = wrap(doThing)
wrappedDoThing('one', 'two', 'three')
doThing('one', 'two', 'three')
We have the wrap
function that takes the someFunction
function.
Then we define the wrappedFunction
function inside the it that takes an unlimited amount of arguments.
We use the rest operator to get all the arguments and put them into the args
array.
Next, we define the newArgs
array with all the args
spread into the array.
And we put 'another argument'
into it as its last element.
Then we call someFunction
with newArgs
‘s element as the arguments by spreading it.
Finally, we return the wrappedFunction
function.
Next, we have the doThing
function that takes an unlimited number ofd arguments and we get them with the rest operator in an array and log them all.
Then we call wrap
with doThing
and assign it to wrappedDoThing
.
Now we call wrappedDoThing
and doThing
with the same arguments.
And we should see:
"do thing", ["one", "two", "three", "another argument"]
"do thing", ["one", "two", "three"]
logged in the console.
We see that the first entry has an extra argument since we called wrappedFunction
which is returned in wrap
.
That added the extra argument.
Conclusion
To wrap a function with JavaScript, we can return a function inside a function.