Skip to content

"(a ?? b) || c" in reactive expression compiles to invalid Javascript syntax #5558

Description

@dimfeld

Describe the bug

With a reactive expression like (a ?? b) || c, the parentheses are stripped and it renders in the output as a ?? b || c, which some later parser stage (in the bundler I think) does not like.

This might actually be a problem with some dependency of Svelte that deals with JS parsing, but I'm not sure, so filing here first.

Logs

Trying it in the REPL reports this error:

Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses (Note that you need plugins to import files that are not JavaScript)

On my local setup with Babel, I see a similar error:

[!] (plugin babel) SyntaxError: Overridable.svelte: Nullish coalescing operator(??) requires parens when mixing with logical operators (150:57)

Also manually confirmed that Chrome and Node throw a SyntaxError when the parentheses are missing.

To Reproduce

REPL: https://svelte.dev/repl/ece0d31ee4d44ef380b2b3d1ee1d3603?version=3.29.0

The invalid expression is on line 35 of the generated output.

Or just use this Javascript.

$: usedValue = (1 ?? 2) || 0;

While the example here just uses constants, the same behavior occurs with normal variables.

Expected behavior

Preserve the parentheses in this case.

Notably, when the parentheses are around the logical operator like 1 ?? (2 || 0), the output still contains the parentheses.

Information about your Svelte project:

Locally, Svelte 3.29.0 with Rollup 2.26.11 and Babel 7.11.6 with preset-env: { esmodules: true }

Also reproduces in the REPL with the above link.

Severity

Low. In my case a ?? b ?? 0 works just fine and it could also be worked around by breaking it into 2 expressions if necessary.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions