...

Variable Scope: Why Variables Are Destroyed

In the previous lesson, we learned to declare a variable first, then assign values to it inside if-else blocks. But why can't we just declare the variable inside the blocks instead?

Run the code in this example to see what happens when you declare variables inside if-else blocks, and then try to use them outside the block.

What Went Wrong?

The code example throws an error because variables declared with let inside curly braces { } only exist within those braces. The variable action is destroyed as soon as the closing brace } is reached.

Run the code step-by-step to see the failure. Then fix the code by with the following steps:

  1. Declare the variable action before the if-else blocks.
  2. Remove the let keyword from inside the blocks.
Loading...

Output (Console)