How can JavaScript Error be both a function and a class?

calin92540842 profile image PDS OWNER CALIN (Calin Baenen) ・1 min read

I just realized this applies to most JS constructors, such as String

I was wondering, how is JavaScript Error both a function and a class?
Now wait, before you tell me, yes, I know, a class is syntactical sugar for a constructor function. BUT! When you use a JavaScript ES6 class, you ALWAYS have to use the new keyword, no matter what.
But, with Error this is ignored.

throw Error("Custom Error"); // Uncaught Error: Custom Error
throw new Error("Custom Error"); // Uncaught Error: Custom Error

So two questions:

  • How does this work?
  • Can I replicate this myself?

  • Thanks!


    markdown guide

    JavaScript regular functions (not arrow functions) are constructible. Meaning that you can create an object using them just like a class. In other words, there is no class in JavaScript and what you recognize as a "class" in JavaScript is just a way to define JavaScript's prototype-based system. So a JavaScript function can be instantiated with the "new" keyword.
    Check out this link for more information: w3schools.com/js/js_object_constru...


    I knew the part about classes not existing, more as I didn't know the new keyword could be used with plain functions.


    This is part of the problem with just learning to use Class in JS. It masks the prototype system underneath, which some beginners don't understand or even know exists

    Yeah exactly!
    I think JavaScript's prototype system is awesome. I think I never used JavaScript's class-based system except for a few times that I had to use.

    • function keyword -- both new and without are possible
    • Arrow functions -- cannot use new (will throw error if you try otherwise)
    • Class constructor -- new is needed (will throw error if you try otherwise)

    I learnt this, when I was trying to find Types-of-Everything.


    Yes you can replicate it yourself, just check if this is an instance of the constructor and if it isn't, call the function with new internally

    function doSomething(message) {
        if (this instanceof doSomething) {
            this.message = message
        } else {
            return new doSomething(message)
    console.log(new doSomething("2"))

    Not sure it's particularly wise to do it though, just seems like it will cause confusion and inconsistency down the road.


    Yup, I definitely agree with refraining from its usage. The Error "class" is pretty much just an exception to the rule, not a robust language feature.