Search code examples
sveltesvelte-3

Why does svelte put curly braces on scalars?


E.g. this from the docs:

<canvas
    width={32}
    height={32}
></canvas>

What purpose do the curly braces serve here?


Solution

  • In the example you showed, it doesn't make a difference. The following are equivalent.

    <canvas width={32} height={32}></canvas>
    <canvas width="32" height="32"></canvas>
    

    However, using the curly braces causes Svelte to interpret it as a JavaScript expression. This means you can do math inside the curly braces...

    <canvas width={32 + 8} height={32 - 8}></canvas>
    

    ...or swap it out for a variable.

    <script>
      let size = 40;
    </script>
    
    <canvas width={size} height={size}></canvas>
    

    Always writing curly braces means that it saves a few keystrokes if you want to make the values dynamic later, but otherwise doesn't impact how the component is rendered.