48

When using reactive variables by declaring them using the $: syntax, you get the following error.

Cannot access 'variable_name' before initialization

Here is the code:

App.svelte

<script>
    import { ledzep, redhotchilis } from './data.js'
    
    $: bandmembers = [...ledzep, ...redhotchilis]
    
    let namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {               
                return true;
            }
        else {
            return false
        }
    })
    
</script>
<h2>Band Members</h2>
<ul>
{#each bandmembers as member}
    <li>{member}</li>
{/each}
</ul>

<h2>Members with "A" in their names</h2>
<ul>
{#each namesWithA as member}
    <li>{member}</li>
{/each}
</ul>

data.js

export const ledzep = ["Jimmy Page", "John Bonham", "Robert Plant", "John Paul Jones"]
export const redhotchilis = ["Anthony Kiedis", "Flea", "Chad Smith", "Josh Klinghoffer"]
johannchopin
  • 13,720
  • 10
  • 55
  • 101
ivan quintero
  • 1,240
  • 3
  • 13
  • 22

1 Answers1

33

When you assign variables using $: you cannot assign them as part of other variables declared using let, const, or var.

When you do assignments using $:, you can only use them in other variables assigned using $:. In the code posted above, you need to change the following lines:

let namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {               
                return true;
            }
        else {
            return false
        }
    })

to the following:

$: namesWithA = bandmembers.filter(d => {
            if (d.indexOf('a') > 0) {               
                return true;
            }
        else {
            return false
        }
    })

It took me a while to figure this out and just wanted to share this with any other Svelte newbies that are starting out in this new technology.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
ivan quintero
  • 1,240
  • 3
  • 13
  • 22
  • 15
    Just noting that in this example, you don't need to use `$:` at all, since `ledzep` and `redhotchilis` aren't reactive variables (values imported from another module are taken to be constant) – Rich Harris May 27 '19 at 09:25
  • It's interesting that if the variable is coming as a parameter, used in the function body and then declared with let, it will raise the error too. – Guilherme Sampaio Aug 03 '22 at 13:27