Question about scoping

I’m doing the JavaScript course and currently on the scope section, on the page titled “Practice Good Scoping”. The exercise is designed to show how important it is not to have variables in different code blocks that conflict with each other.
I can complete the exercise fine but I’m unsure what the point of having different variables is.
This is the code completed in accordance with the instructions:

const logVisibleLightWaves = () => {

  let lightWaves = 'Moonlight';

  let region = 'The Arctic';

  if (region === 'The Arctic') {

    let lightWaves = 'Northern Lights';

    console.log(lightWaves)

  }

  

  console.log(lightWaves);

};

logVisibleLightWaves();

I don’t see why I need to bother with defining the variable lightWaves at all, let alone twice. Why can’t the code just be:

const logVisibleLightWaves = () => {

  let region = 'The Arctic';

  if (region === 'The Arctic') {

    console.log('Northern Lights')

  }

  

  console.log('Moonlight');

};

logVisibleLightWaves();

This gives the same answer, is quicker, and has no risk of scope pollution. Presumably there is a good reason for needing the lightWaves variable but I am very new to this so can’t work out what it might be.
TIA for your help

Not really. It is simply to illustrate the different scopes.

Ah ok so just for teaching purposes then! I was just wondering whether there was an actual code-related reason that I wouldn’t understand until I knew more but that makes sense, thanks.

1 Like