Javascript: Undefined parameters
When writing a function that expects arguments you may need to ensure an argument has a default value.
function badPractice(a) { var _a = a || 'a was undefined?'; console.log(_a); }
I see this a lot in open source code and frequently at companies and agencies and it concerns me. In very few cases it's intentional, in most cases the developer doesn't expect to get unpredictable input.
// expected behaviour badPractice() // 'a was undefined?' badPractice(void 0) // 'a was undefined?' // unexpected bahaviour badPractice(0) // 'a was undefined?' badPractice(false) // 'a was undefined?' badPractice(null) // 'a was undefined?'
The problem is that if you pass a falsey value for a
, the expression will set a
to the default value.
function goodPractice(a) { if(a === void 0) { a = 'a was undefined'; } console.log(a); } // expected behaviour goodPractice() // 'a was undefined' goodPractice(void 0) // 'a was undefined' goodPractice(0) // 0 goodPractice(false) // false goodPractice(null) // null
Ok, so this is a major improvement. Not only are we properly checking for a truly undefined
value, but we have a consistent pattern with instances when we actually need to run more code within the conditional or require finer control over the conditional logic itself. void
is just an operator that evaluates any expression to undefined
, by convention we use void 0
. Even if we have var undefined = 5;
somewhere in the code void 0
will still be evaluated to a true representation of undefined
.
The problem with the good practice approach is that the majority of Javascript developers aren't familiar with void 0
— especially not beginners. While you can train yourself to read it as "undefined" it still takes a second for the reader to translate the words void 0
into "undefined".
So let's follow best practices, be explicit, and follow a consistant pattern.
function bestPractice(a) { if(typeof a === 'undefined') { a = 'a was undefined'; // other conditional logic here } console.log(a); } // expected behaviour bestPractice() // 'a was undefined' bestPractice(void 0) // 'a was undefined' bestPractice(0) // 0 bestPractice(false) // false bestPractice(null) // null
Leave a Comment | Apr 14, 2013