You're asking a lot of questions, most of which are duplicates. However, I know it can sometimes be hard to piece together many different answers to find the answer to your own question. In the future, you should avoid asking more than on question in a post. It will make some people less angry.
I'll add some comments to the code inline
function logAndReturn(func) { // <------------┐
return function() { // <------------------┐ |
// `arguments` belongs to this function-┘ |
// NOT this one --------------------------┘
var args = Array.prototype.slice.call(arguments);
// `apply` expects an array but `arguments` is an object
// we call `slice` on `arguments` so that it can be converted to an array
var result = func.apply(null, args);
console.log('Result', result);
return result;
}
}
var addAndLog = logAndReturn(add);
In reality, JavaScript is a lot more forgiving than this tho. It's not a typed language, so I kind of lied when I said apply
expects an Array. Sure, it'd be nice, but it's also not going to cry if you give it an array-like object
function theHiddenTruthBehindArguments() {
console.log(arguments)
console.log(arguments.length)
}
theHiddenTruthBehindArguments(0,1,'abc')
// {"0":0,"1":1,"2":"abc"}
// 3
arguments
is actually an array-like object. It has sequential numerical keys (beginning with 0) and a length
property which is all the information required to treat any object like an array.
So this would actually work
function logAndReturn(func) {
return function() {
// this works too !
var result = func.apply(null, arguments);
console.log('Result', result);
return result;
}
}
var addAndLog = logAndReturn(add);
And to answer your last question, apply
woks in a pretty simple way …
let args = [1,3,4]
func.apply(null, args)
… is (mostly) the same thing as …
func(1,3,4)
This one you can read the dupe question for. There a couple details you might need to know.
That function you gave can be expressed better in ES6 and I think it'd be a lot less confusing for you
function logAndReturn(func) {
// rest parameter ...args is the new way to express variadic functions
// (functions that take a variable number of arguments)
// all arguments given will be collected in a single `args` array
return function(...args) {
// spread syntax will expand the array to call `func`
// with all of the collected args
var result = func(...args)
console.log('Result', result)
return result
}
}