Cannot access ‘variable_name’ before initialization – Svelte Error

Svelte throws the error, Cannot access ‘variable_name’ before initialization, when we try to assign reactive variables declared using $: to non-reactive variables like const, var, let etc.

Consider this example –

<script>
$: superhero = ["Ironman", "Thor", "Hulk", "Superman", "Spiderman", "Antman"]

let superHeroWithMan = superhero.filter(hero => hero.indexOf('man') > 0)
</script>

<h3>All Superheroes</h3>
<ul>
{#each superhero as hero}
    <li>{hero}</li>
{/each}
</ul>

<h3>Superheroes with man in name</h3>
<ul>
{#each superHeroWithMan as hero}
    <li>{hero}</li>
{/each}
</ul>

This code will throw the error that variable_name cannot be accessed before initialization. This is because superHeroWithMan is not initialized and we are using it in loop while displaying list. Why it is not initialized? Because we cannot use a reactive variable with let, const, var etc.

The correct way of doing this is –

<script>
$: superhero = ["Ironman", "Thor", "Hulk", "Superman", "Spiderman", "Antman"]

$: superHeroWithMan = superhero.filter(hero => hero.indexOf('man') > 0)
</script>

    Tweet this to help others