How to set a default value for a function's paratemer in Javascript
There are two very important things when it comes to a Javascript function: knowing how to set a variable number of parameters and knowing how to set a default value for a parameter. This article is about the latter.
Using a function with a default value for a parameter is something I often do because it comes in handy during those times when you have a function used with only a certain value in 90% of the cases.
Let's take this zero-padding function, that transforms number like 1 or 13 in 0001 and 0013.
/**
* Adds zero-padding to a number (ex. 1 becomes 0001)
*
* @method zeroes
* @param {Number} number : The number to be padded
* @param {Width} width : The length of the number after the padding
* @return {Number} The padded number
*/
function zeroes(number, width) {
var fillZeroes = "000000"; // max number of zero fill ever asked for
var input = number.toString(); // make sure it's a string
return (fillZeroes.slice(0, width - input.length) + input);
}
Most of the times I'm using it in the project I'm currently working on, I use it with a width of 4 but I might just need it in a different situation, with another width.
In its current form, I would have to use it like zeroes(1, 4) (return "0001") every time I want to do a default padding of 4 digits.
In order to be able to use it like this
var nr1 = zeroes(1);
var nr2 = zeroes(1, 6);
//nr1 = 0001
//nr2 = 000001
I need to set a default value of 4 for the width. So we do this the following way:
function zeroes(number, width) {
"use strict";
width = (typeof width === "undefined") ? 4 : width; //defaults to 4
var input = number.toString(); // make sure it's a string
return (fillZeroes.slice(0, width - input.length) + input);
}
All the magic is done with this line of code:
width = (typeof width === "undefined") ? 4 : width; //defaults to 4
If no value is detected for width, when the function is called, it sets its value to 4, otherwise it just leaves the variable alone. This line can be rewritten in a more beginner friendly way, for those who don't understand yet the short-circuit evaluation.
if(typeof width === "undefined") {
width = 4;
} else {
width = width;
}
In order to make things easier to write and remember, you can also wrap it up in a defaulting function, like this:
function defaults(param, defaultValue) {
return (typeof param === "undefined") ? defaultValue : param;
}
Then, the zero-padding function will look like this:
function zeroes(number, width) {
"use strict";
width = defaults(width, 4);
var input = number.toString(); // make sure it's a string
return (fillZeroes.slice(0, width - input.length) + input);
}
And there you have it!