Hacker News new | ask | show | jobs
by ahoge 4053 days ago
> The behavior of Number, Boolean, String, and Array is well-defined, it's safe to call them without new.

ES6 is packed with weird but well-defined things.

The problem is that calling a constructor function (a PascalCase'd function) without `new` looks like an error because it generally is an error. To make matters worse, without closely examining that function, you cannot tell if it's an error.

I do know that `Number()` happens to be one of those constructor functions which not only work without `new`, it also happens to behave differently when `new` is missing. It does not return an object. It returns a primitive.

Someone who doesn't know about this unusual secondary function will waste some time if they spot this apparent mistake.

Now, to defuse this time-wasting trap, you could either add a comment... or just do the sensible thing and write it in a way which does not require a comment.

1 comments

That's fair, I just find them super useful in various situations, for example filtering over an array with Boolean to remove falsey values.