forward all arguments to another function [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 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);

Related

Javascript is it bad practice to return an object that is passed by reference [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 11 months ago.
Improve this question
Let's say I have this function in JavaScript:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
b = foo(b)
console.log(b)
Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
foo(b)
console.log(b)
Is it bad practice to use return b for better readability even though it is not needed
Are there any downsides to returning the object?
You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.
However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.
Following that idea, your example would look like:
function foo(a) {
// Copy our input (assuming 'a' only contains primitive values)
const output = { ...a };
output.item = 'four';
return output;
}
const b = { item: 'three' };
const c = foo(b);
// b is unchanged
The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.
Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.
sorted_words = string.split(" ").sort();
If it didn't return the array, you'd have to do this in two steps:
sorted_words = string.split(" ")
sorted_words.sort();

Is this a valid arrow function? [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 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
This question is from an online quiz and I'm confused by it. I feel its the third one but I get undefined.
Which choice is an example of an arrow function, if c is defined in the outer scope.
a,b =>c;
{a,b} => c;
(a,b) =>c; //this one.
a,b => {return c;}
The question is primarily asking about syntax. The third option is indeed the correct choice, because the function parameters a and b must be enclosed in parenthesis ( and ).
You get undefined because c must first be defined.
var c = 'foo'; // define c in outer scope
var f = (a,b) => c; // define the arrow function
var result = f(1,2); // invoke the arrow function with some parameters
console.log(result); // examine the output is 'foo', the value of c
Only the second one has invalid syntax.
The first and last one are also valid, and employ the comma operator, with the arrow function being the right hand operand. You'll still get a run time error if a is not a defined variable, but once it is, it is valid:
let a; // define
a,b =>c; // valid
a,b => {return c;} // valid
console.log("ok");
The third one would be the evident choice; it is also the only valid arrow function that does not need a to be defined in the outer scope.
If you call these valid functions, then c needs to be defined, which seems to be guaranteed.

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]);
}

How might the syntax `foo(a)(b)` be useful? [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 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.

Is it better to "overload" a function or have two separate functions when dealing with multiple argument types [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 8 years ago.
Improve this question
I'm writing a function that takes a array of word objects, and then modifies the word objects. I would like a user to be also be able to use the function on an individual word object, and I'm wondering which is a better approach:
a) have the function type check whether an inputted argument is an object or array and respond accordingly
b) have two functions, one for an obj, and the other for an array.
//method 1: accepts either a obj or an array
function wordChecker(element) {
if (typeof element === 'object') {
wordCheckerHelperHelper([element]);
} else if(element instanceof Array) {
wordCheckerHelper(element);
} else throw new Error('invalid argument');
};
function wordCheckerHelper(arr) {
//do something
};
//method 2: separate methods, but the wordCheckerObj method is just a wrapper around the wordCheckerArr method
function wordCheckerArr(arr) {
//do something
};
function wordCheckerObj(obj) {
if(typeof obj !== 'object') throw new Error('invalid argument');
workCheckerArr([obj]);
}
JavaScript libraries tend to use first approach, i.e. accept any type of argument and try to deal with it somehow. I guess this is mostly because of JavaScript dynamic nature, users would quite often don't know (or not sure) about the type of object they received from other system/library. Type detection in JavaScript could be quite tedious, and user code would end up being a massive amount of ifs and switches, so this types of checks are better encapsulated on library level.

Categories

Resources