Posts

Showing posts with the label coercion

Coercion Performances

There are cases where JS coercion may be wanted/needed/necessary, at least logically speaking. A classic case is a list of primitives, e.g. strings, or numbers, and a check we would like to perform without creating a new function each time . // recycled function function alreadyThere(value) { // wanted coercion, no cast needed return value == this; // shitty code, logically speaking // one cast per iteration return value === "" + this; } var listOfNames = ["Me", "You", "Others"]; // the pointless check listOfNames.some( // the recycled callback alreadyThere, // the *passed as object* this "You" ); // will be true Now, for above specific case anyone would use an indexOf but this is not the point. The point is that in some case we may want to do more complicated stuff and compare the result with this // know if word was already in the dictionary function alreadyThere(value) { return value.toLowerCase() == this; } // co...

JavaScript Coercion Demystified

This post is another complementary one for my front-trends slides, about performances and security behind sth == null rather than classic sth === null || sth === undefined . I have already discussed about this in my JSLint: The Bad Part post but I have never gone deeper into this argument. Falsy Values In JavaScript, and not only JavaScript, we have so called falsy values. These are respectively: 0, null, undefined, false, "", NaN . Please note the empty string is empty, 'cause differently from php as example, "0" will be considered truish, and this is why we need to explicitly enforce a number cast, specially if we are dealing with input text value. In many other languages we may consider falsy values even objects such arrays or lists: <?php if (array()) echo 'never' ; ?> #python if []: print 'never' Above example will not work in JavaScript, since Array is still an instanceof Object. Another language that has falsy values is the ...