2

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
2

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:

  1. The arguments.length property is coerced from a number to a boolean value to see if there are elements in the arguments pseudo-array.
  2. Both the global console object and its log method are coerced from objects to boolean if they are not null, which prevents an (old?) IE bug where console.log would cause errors if called without the developer console open.
  3. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.