Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For what reason stack property is optional in Error?

In an Error, the property stack is optional. However, when I throw a new Error('myError') or when I have a generic error thrown during the execution of my script, I always get the stack. According to the browser, the stack is not the same but I is not undefined.

  • I was wondering in which case it was possible to have an undefined stack?
like image 641
PierBJX Avatar asked Mar 18 '26 04:03

PierBJX


1 Answers

The stack property is not defined by the JavaScript specification (yet). So a compliant JavaScript implementation could well not have a stack property on Error instances. Most do nowadays (certainly the big three: V8, SpiderMonkey, and JavaSciptCore), but it's not standardized (yet), so they don't have to.

In an Error, the property stack is optional.

I'm guessing you're referring to TypeScript's type information for Error:

interface Error {
    stack?: string | undefined;
}

Since most JavaScript engines do provide a stack property of type string even though it's not defined by the specification, making it optional with the type string | undefined is a pragmatic choice (the TypeScript project team are notoriously pragmatic). So rather than leave it out entirely, they acknowledge the common practice.

I was wondering in which case it was possible to have an undefined stack?

I think it's unlikely you'd have an undefined stack on an Error instance on implementations that support it (more likely "" if no stack information is available, but I don't recall seeing a blank stack). That said, there's likely a reason TYpeScript's types define it as stack?: string | undefined and not stack?: string.

like image 115
T.J. Crowder Avatar answered Mar 20 '26 17:03

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!