If you want to chain them, then you'll have to add these methods to the string prototype:
String.prototype.prepend = function() {
return 'foo ' + this
};
String.prototype.exclaim = function() {
return this + '!'
}
var s = "".prepend().exclaim();
console.log(s);
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 undefined
in the function. Since null
implicitly converts to undefined
, that's often handled by checking those parameters for null
var exclaim = function(str, ch) {
if (ch == null){
ch = '!';
}
return string + ch
};
You'll often also see something like this:
var exclaim = function(str, ch) {
ch = ch || '!';
return string + ch
};
That's similar, but will overwrite any of the 6 "falsy" values: null
, undefined
, NaN
, 0
, false
and ''
(empty string). So if you were to do that, and try to pass an empty string in for ch, it would be overwritten.