How might the syntax `foo(a)(b)` be useful? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Today I have found a strange way of adding 2 numbers in javascript:
Basically the call of the method looks this way: add(5)(6) and the declaration of the method is:
function add(x) {
return function(y) { return x + y; };
}
Ok, I got it. The add function does not return a number, but returns the anonymous function which adds the first number with the second. But what is the point (how it can be helpful)?
Where exactly can it be useful apart from puzzling other people or writing some sort of obfuscated malware?

Obviously, the call add(5)(6) is not too useful - you'd rather write 5 + 6, or, if it's really a function, add(5, 6).
The great benefit is in functional programming where you are supposed to pass a function around (callback!) - most prominent in the array utils. For example:
[1, 2, 3].map(add(5)) // [6, 7, 8]
You can also use this for the composition of quite complex functions, without having to deal with function expressions. If we didn't have this curried add function, in the above example we would have needed to write
[1, 2, 3].map(function(y) {
return 5 + y;
}) // [6, 7, 8]
…and that every time for each different x.

Lets have a look at a function which is bit more common in the wild, pluck:
function pluck(prop) {
return function(obj) {
return obj[prop];
}
}
This function accepts a property name and returns a new function which, given an object, returns the property of that object.
This is useful for mapping an array of objects to an array of a specific property of those objects:
var names = people.map(pluck('name'));
Now, if you just have to do this a single time, there is no need to create a dedicated pluck function. However, if you do this multiple times, it avoids code repetition.

You wouldn't necessarily use it as you've described, but perhaps if you want to pass around a function that "adds 5 to the result", you could do
var addsFive = add(5);
// some other code, perhaps passing this var to another function
var result = addsFive(6); // returns 11
This technique of "partial" function invocation is called currying - this other SO question goes into some details on how/where it can be useful, as well as provides several links to help explain the concept.

Related

forward all arguments to another function [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
In ES6, it's possible to use ...arguments to pass all arguments of one function to another, e.g.
function foo(a, b) {
return bar(...arguments);
}
function bar(a, b) {
return a + b;
}
foo(1, 2); // returns 3
I "discovered" this idiom myself, and am wondering if there are any downsides to it, or whether it's considered a bad practice?
...am wondering if there are any downsides to it...
Not really, other than a couple of points to be aware of:
arguments in loose mode has some minor performance problems (nothing to worry about in normal situations).
Arrow functions don't have their own arguments, so that won't work in an arrow function; you'll either get a ReferencError (if the arrow function is at the top level) or the arguments from the nearest containing function function (or method) (because arrows close over arguments [and this and super]), which may not be what you want.
You're using spread notation, so you might consider using rest notation as well:
function foo(...args) {
return bar(...args);
}
function bar(a, b) {
return a + b;
}
console.log(foo(1, 2)); // returns 3
That doesn't have the (minor) performance issues with arguments, works in arrow functions, and is clear about what you mean.
not really any downsides, you just have to make sure that if your arguments is an array, that it is in the right order for the arguments of the function that you are calling.
arguments variable in the function contains all arguments passed to the function. This can be used if you have various number of parameters and you don't know how many.
Starting from ES6 if you want to pass into the function various number of parameters, you can use rest parameters.
function foo(...rest) {
return bar(...rest);
}
function bar(a, b) {
return a + b;
}
foo(1, 2);

Is a function with nested functions considered a single function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm new to JavaScript and working on a coding challenge as part of a bootcamp application process.
The question requires writing a single function to accomplish a task.
Although I've looked far and wide, I've yet to come across an answer.
If I write a function that contains other, nested functions, would that still be considered one function?
If I write a function that contains other, nested functions, would that still be considered one function?
Yes. A function is an encapsulation unit, it's a blackbox. You can call it, and get results back, but how it is implemented does not matter when looking from outside. A function that modularises its internal implementation into multiple local function is indistinguishable from one that does not as long as it behaves the same.
Yes.
From a technical perspective you can't even write a function that doesn't call use nested functions. The act of declaring variables alone is going to call a chain of functions to allocate memory which in turn eventually calls functions in assembly which then calls functions in your processor to which calls functions to your memory driver which calls.
Similarly calling operators to set or manipulate your variables are function calls which are all layered APIS calling a chain of functions.
Suppose you write a function min that looks like this:
function min(a,b) {
return Math.min(a,b);
}
This is still a single function even though it is calling a global function.
The same logic applies if you write an internal function for a complex object
function min(data) {
var smallest = function(a,b) {
if (a.x<b.x) { return a;}
else if (a.y>b.y) { return b;}
else if (a.y<b.y) return a;
return b;
}
return smallest(data[0],data[b]);
}

What to think about before defining function as Object.prototype extension or just function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
For example I have to add 'foo' to string.
So I have at least two ways to go.
First, I can implement String.prototype.foo:
String.prototype.foo = function() {
return this + 'foo';
};
var s = 'str';
var data = s.foo(); // "strfoo"
Another way:
function foo(str) {
return str + 'foo';
}
var s = 'str';
var data = foo(s); // "strfoo"
Both look pretty. But should I think about any "underwater rocks" before choosing first or second implementation? Are there any significant reasons, such as efficiency and performance?
The first extend the functionalities of String.
Use this solution if you have a class of objects and you like to add new behaviours to it.
The second is more an utility function.
Note also that you can apply the second foo also to a variable that is not a String, so you should also test the type of the argument if you like to limit the use to a String argument.
Modifying the globals in JavaScript is always a bad decision. Don't do that, except if it's not about making a polyfill.
The implications are multiple from your code being not portable to probability of breaking someone else's code.
I would always use the second method. Or if things are really that complicated maybe implement my own class of String.
function MyString(str) {
this.str = str;
}
MyString.prototype.foo = function() { return this.str + "foo" };
var s = new MyString("str");
var data = s.foo(); // "strfoo"
Here is further reading about modifying global objects and the downsides :
https://softwareengineering.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea

What do you call this programming pattern? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to figure out how to do this in JavaScript and can't seem to find the right words to Google for it. It's a fairly common pattern.
someOperation(obj) { resultOfSomeOperation ->
anotherOperation(resultOfSomeOperation)
}
Presumably someOperation is a method that takes as arguments an obj, and a function with signature result -> ??. What do you call this?
I believe the pattern you're pointing to is the "Callback" pattern, or more generally "Higher Order Functions", in which a function takes in a function as a parameter, and then uses the passed in function in some way. Some examples would be Each, Map, Reduce, etc... These often use lambda functions.
Here's some information on these topics: Callbacks on Wikipedia, JavascriptIsSexy Callbacks, Eloquent Javascript Chapter 5.
I'm leaning on Javascript examples, because that's the tag you used. Feel free to ask me clarifying questions and I can explain them further.
Here's an example:
var exampleArray = [1, 2, 3, 4, 5];
exampleArray.map(function(num){
return num * 2
});
// Returns [2, 4, 6, 8, 10];
As you can see, map makes use of the anonymous function that was passed in. Map applies the given function to each element of the array, and returns those outputs to a new array. This could also be done by defining the function ahead of time, and passing it in by name.
var exampleArray = [1, 2, 3, 4, 5];
var doubleValue = function(num) {
return num * 2;
};
exampleArray.map(doubleValue);
// Returns [2, 4, 6, 8, 10];

Why does the new Function() return this output? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was reading Chapter 4: Functions() of the book Javascript Enlightenment by Cody Lindley.
http://jsfiddle.net/4a860dkg/
I was playing around with functions and wanted to know why in the fiddle addNumbersA returns anonymous(num1, num2, /**/) rather than returning a function()
Can anyone tell me why does this happen?
EDIT:
1. What I want to ask is that why doesn't logging addNumbersA return me a function() as it must do.
2. When I use typeof(addNumbersA), I get a function and not a function() - whereas addNumbersB returns function().
Apologies if i'm not clear enough.
The reason console.log(addNumbersA); returns:
function anonymous(num1,num2
/**/) {
return num1 + num2
}
Is because its a functional expression. The function keyword, when used as an expression, can create a function value. A function value can do all the things that other values can do—you can use it in arbitrary expressions, not just call it. It is possible to store a function value in a new place, pass it as an argument to a function, and so on.
Similarly, console.log(addNumbersB); returns:
function (num1, num2) {
return num1 + num2;
}
You can test this out in chrome dev tools, perhaps some inspectors/js repls have different notations of shortcutting, such that you may not get EXACT output (ie. just get 'function()' in Firebug).
Function is a constructor for function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
When you define a function as an instance of Function constructor, it is not compiled but stored as a runtime string. That's why it shows up as a function definition and not as a function object.
They will function the same except because it is compiled at the time of execution, it only has the global closure and has no knowledge of the local closure except for its own local variables.
console.log(addNumbersB); // logs function() correct!
This will not run the function, which your are expecting.
This does:
console.log(addNumbersB(2,2)); // logs 4 correct!
The above returns 4 because we call the function and pass the two numbers which are then added by the function;
The first example you give is a method rarely used for normal day to day coding, it creates a function from a string that represents valid code.

Categories

Resources