When is type coercion a good idea?
https://softwareengineering.stackexchange.com/questions/226104
-
02-10-2020 - |
Question
When do you want (on purpose) to coerce type in JavaScript? I mean, beyond comparing strings and numbers, when does it benefit something you're building?
Examples of type coercion:
"The answer is " + 42
//=> "The answer is 42"
"37" - 7
//=> 30
"37" + 7
//=> "377"
var foo = [0];
console.log(foo == foo);
//=> true
console.log(foo == !foo);
//=> true
Solution
The fundamental principle that most affects type coercion is be liberal in what you accept. For a language with argument types are part of a function signature, you could handle, say, a log
function by requiring string
parameters and having overloads for object
and integer
and whatnot.
In JavaScript, which is so loosely typed that you should treat function arguments as simply a naming suggestion for the first X arguments passed, type coercion can be used to help quickly handle most argument types. And, of course, it's a fundamental aspect of feature inspection. Consider the following, which will take any number of arguments and pass them to console.log
as a single space-seperated string:
function toLog() {
if(arguments.length && window.console && window.console.log) {
var ArgString = "";
for(var a = 0; a < arguments.length; a++) {
ArgString += arguments[a];
}
console.log(ArgString);
}
}
The above uses type coercion in three ways that are extremely useful for JavaScript:
- The
arguments.length
property is coerced from a number to a boolean value to see if there are elements in the arguments pseudo-array. - Both the global
console
object and itslog
method are coerced from objects to boolean if they are not null, which prevents an (old?) IE bug whereconsole.log
would cause errors if called without the developer console open. - By setting
ArgString
to an empty string""
on initialization, we signal to the interpreter to coerce all arguments to strings as well. Which isn't all that useful on a modern browser, but works for the sake of our example.