Cargo Cult Code Generation

Javascript Errors in the Wild Recently, I came across this code in the popular Axios library: function AxiosError(message, code, config, request, response) { Error.call(this); // some more code i've left out for brevity } What does Error.call(this) do, you might ask? Nothing! I’ve tried it out in Node versions back until 6, Spidermonkey and JavaScriptCore. None of them do anything to the this object of the Error constructor. Moreover, the specification says that you have to be able to call the Error constructor without new, so it makes sense to implement it that way.
Read more →

String Representations of Javascript Objects

toString() and Symbol.toStringTag The default Object.prototype.toString() function is defined to the specification to return [object X] even for non-objects: Object.prototype.toString.call(undefined) // returns "[object Undefined]" Object.prototype.toString.call(true) // returns "[object Boolean]" {}.toString() // returns "[object Object]" X is a so-called ‘string tag’ and in newer versions of Javascipt, you can set it yourself: {[Symbol.toStringTag]:"MyObject"}.toString() // returns "[object MyObject]" But for objects, you can also just implement the complete toString function: {toString: ()=> "My Cool Object!
Read more →

How to detect Errors in JavaScript

TL/DR Finding out if an object is an error is unreliable and full of edge-cases. A modern, isomorphic but still not perfect way to do it is the following1: function isError (object) { return object instanceof Error || ( object?.constructor?.name === 'Error' || object?.constructor?.name === 'DOMException' ) } Many custom error classes in the JavaScript ecosystem are hard to detect because creating custom error classes used to be hard before the introduction of the class syntax.
Read more →