JavaScript Scope

What does it mean by “new days variables are being defined in the scope of each if/else if”… I thought the days would come from the declared days about the if/else if statements… When it asks to delete lets… Does it mean to just erase the “let” and not the “let days = 200;” ?

When the “let” alone is removed is it just pulling from the original declaration above the if/else if statement?

1 Like

Scope, in a roundabout sense, refers to the areas of your program where things are accessible.

For example:

let someNumber = 4;
function doNothing() {
    let someText = "Woohoo!";
}

someNumber here has global scope, whereas someText exists only within the scope of the doNothing function.

So, in your code:

const days = "";
  if (event === 'Marathon') {
        let days = 50;
    }

the const days has global scope, whereas we’re redefining the variable - using let - within the scope of the if-else structure further down. You need a const/var/let keyword when declaring a variable, not to assign one.

An analogy around scope

Perhaps this can make scope a bit clearer.

Consider this. The sky is visible from anywhere - look out a window, there it is. You could say that the sky has a global scope.

Equally, your computer is only visible inside of your house. Only people inside your house can see your computer, so you could say that the computer has a scope of inside your house.

That’s the first place, in your screenshot anyway, where the variable is declared and initialised. Each let days =... statement is *re-*declaring the same variable.

Yes, it means to remove just the let keyword - not the entire line, as doing that would mean there’s no code in any of your if-else structure. :slight_smile:

Precisely; once the let keywords are removed we will have a single declaration of days: const days = "";. We are then reassigning its value inside our if-else structure… (or, at least, we will try …)