How a callback is being passed in to a function? [duplicate] - javascript

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 3 years ago.
I was given the following solution to an exercise:
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback) {
var newArray = [];
// Add your code below this line
this.forEach(a => newArray.push(callback(a)));
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item) {
return item * 2;
});
the idea is to build your own replacement for .map() method.
My problem is to understand the callback part. So far my understand of a callback, is a funct that is passed into another function (as an arg) and is called after something else.
I cannot see where is another function being passed in as the callback in the solution, so I'm struggling to understand the exercise, mainly: this.forEach(a => newArray.push(callback(a)));
Is there anyone who could clarify this for me?

You can easily visualize synchronous callbacks by replacing the call with the functions code itself.
In your function call, callback is equal to:
function(item) { return item * 2; }
If we insert that into this line:
this.forEach(a => newArray.push(callback(a)));
we get:
this.forEach(a => newArray.push(
/*item = a*/
/*return*/ a * 2;
));
Or in other words, for each a in the array, a * 2 gets pushed to the newArray.

Related

Trying to understand a tricky question on closure/currying [duplicate]

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
Variadic curried sum function
(19 answers)
Closed 5 months ago.
I have been struggling to understand how to solve a problem below. I understand that it involves currying and I was able to come up with the answer if argument in sum() is included. However, I can't figure out how to solve it with sum() being empty.
I was able to come up with a solution for having a function invocation at the end s(1)(), but not for s(1).
var sum = function() { /* put your code here */};
var s = sum();
alert(s); // 0
alert(s(1)); // 1
alert(s(1)(2)); // 3
alert(s(3)(4)(5)); // 12
This is solution that works with all parameters being included and () at the end.
var sum = function(a){
return function(b){
if(b !== undefined){
return sum(a+b);
}
return a;
}
};
For the first s call console.log(s), I was only able to come up with simple solution below, to be able to return 0. It seems to be impossible to return 0 and then return a function such as s(1).
var sum = function(a){
if(!arguments.length) return 0;
};
var s = sum();
console.log(s);

How these inner function parameters are getting a value? [duplicate]

This question already has answers here:
Where do the parameters in a javascript callback function come from?
(3 answers)
Closed 1 year ago.
I saw that function and tried to understand it, but I don't get what are the (a, i) arguments of that function. How they're getting a value assigned to them?
function ftRotations() {
let str = 'abc';
let arr = ['a', 'b', 'c'];
return arr.map(function (a,i) {
return str.slice(i)+str.slice(0,i)
});
}
The map method provides arguments when calling the callback, which are received by the callback in the a and i parameters it declares. (The callback doesn't use a for anything, but uses i. The callback also uses str, which it closes over because the function was created in a context where str exists.)
It may help to see a rough idea of what map does internally:
// Note: VERY ROUGH approximation, leaving out all kinds of details (like `thisArg`)
map(callback) {
// Note: `this` is the array you called `map` on
const result = [];
for (let index = 0; index< this.length; ++index) {
result[index] = callback(this[index], index, this);
// In the callback, ^^^^^^^^^^^ ^^^^^
// becomes `a` −−−−−−−−−−−−−−/ \−−−−−−−becomes `i`
}
return result;
}

JavaScript array expressions return object literal in one line [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
Its known that someone can make a one-line array function like this to return the single value:
var func = (x) => x + 1 //func(2) == 3
and you can also make multi-line array-functions, whose values need to be manually returned:
var funcMultiline = (x) => {
var result = 1;
result += x;
return result;
}
funcMultiline(4) == 5; //true
So the question:
let's say I want to return a new object in one line, if I use the brackets, then the array-function is treated like a multi-line function, and doesn't actually return the object-literal. Is there any direct way to create an object literal in, lets say, a map function? Like:
[...Array(25)].map(e => {x: 5, y:10}) //this is a syntax error, but how can I make this work
Returning object literals using the concise body syntax params => {object:literal} will not work as expected.
You have to wrap the object literal with parenthesis:
var res = [...Array(25)].map(e => ({x: 5, y:10}))
console.log(res);

Calling functions inside of loops and methods doesn't require ()? [duplicate]

This question already has answers here:
Callback function - use of parentheses
(4 answers)
Closed 6 years ago.
Why don't I need to use () to call a function within a 'for' loop or within an '.addEventListener()' method? For example:
function activitiesReset()
{activitiesLegend.style = '';
}
for (var i=0; i<checkboxes.length; i++) {
checkboxes[i].addEventListener('change', activitiesReset);
}
In the addEventListener method, I first tried calling my function like activitiesReset(), but this did not work. Removing the () from the end of the function worked.
Why is that?
checkboxes[i].addEventListener('change', activitiesReset) is not calling activitiesReset. It is passing activitiesReset as an argument. activitiesReset is a function itself; activitiesReset() is a call to a function, evaluating to its return value. You want to set the event listener to your function, not to undefined (which is the result of calling your function).
The key to understanding this is the fact that functions in JavaScript are also values, just like numbers or strings or objects. (In fact, they are a specific kind of object.)
var adderFuncValue = function(x, y) { return x + y; };
function multiplierFuncValue(x, y) { return x * y; };
function callFuncWithTwoParams(func, p1, p2) {
func(p1, p2);
}
callFuncWithTwoParams(adderFuncValue, 3, 5); // 8
callFuncWithTwoParams(multiplierFuncValue, 2, 3); // 6
var someFunc = adderFuncValue;
someFunc(7, 8); // 15
So just like I'm passing functional values into callFuncWithTwoParams, you are passing a functional value into addEventListener. The browser will remember that function and associate it with change event, and call it -- later.

Trying to comprehend a function that has two inputs for parameters in JS (as in functionX(param1)(param2)) [duplicate]

This question already has answers here:
Two sets of parentheses after function call
(4 answers)
Closed 6 years ago.
I'm pretty baffled by this question that I came across for my interview prep. It wants me to be able to write a function called multiply that takes in parameters in this haphazard way:
multiply(5)(6);
I tried to write a callback and then refer to this in the return statement, but it was not kosher.
function multiply(function(value){
return this * value;
});
}
Does this problem require recursion?
Thanks!
If you want to call your function in this multiply(5)(6); way,
Then you must be searching for function currying. And that can be accomplished by,
function multiply(a){
return function(b){
return b * a;
}
}
//your way
console.log(multiply(2)(2)) //4
//The standard way
var multiplyBy5 = multiply(5);
var res = multiplyBy5(3);
console.log(res); // 15;
var multiplyBy10 = multiply(10);
var res = multiplyBy5(3);
console.log(res); // 30;

Categories