JS newbie question here:
Let’s say I have some simple methods for string manipulation, like these silly examples:
var prepend = function(str) {
return 'foo ' + str
};
var exclaim = function(str) {
return str + '!'
}
Now, I can use these like so:
var string = prepend('bar'); // 'foo bar'
string = exclaim(string); // 'foo bar!'
However, I think it would be really neat if I could also, optionally, make these methods chainable, so I could also do something like:
var string = "foo"
string.prepend().exclaim()
… and I’d still get "foo bar!" as my result.
It would be even better if I could also pass optional args into this chain, like:
var exclaim = function(string,char="!") {
return string + char
};
So, my questions are:
-
So basic, but am I describing this correctly? What do you call a method that can be chained like this? And, what do you call the return of the previous method in the chain, the thing that this next method will operate on?
-
How do you set a variable to be either the return of the previous method in the chain, or else provided as an argument?
Thanks!
If you want to chain them, then you’ll have to add these methods to the string prototype:
DEMO
WRT optional parameters, you can take advantage of the fact that in JavaScript, you can call a method without passing values for some of the parameters. Those un-passed parameters will show up as
undefinedin the function. Sincenullimplicitly converts toundefined, that’s often handled by checking those parameters for nullYou’ll often also see something like this:
That’s similar, but will overwrite any of the 6 “falsy” values:
null,undefined,NaN,0,falseand''(empty string). So if you were to do that, and try to pass an empty string in for ch, it would be overwritten.