Functions

Why must I declare days (declared above the if statement)? If I don’t declare it, the code will not run.

Your code should error if any of those if statements are true.

When using let in JavaScript to declare a variable it is scoped (accessible) to the code block (anything in between the { } part) you declared it and other code blocks that sit inside it (in your case the if and else if statements). So if you remove the top level let days = ‘’; then for each let days = x; in the if statements, the days variable will only exist in the if statement and not outside it.

Your code doesn’t show it but you must have been returning days, without the top let days = ‘’; part there is no days variable in scope that can be returned, hence why it was erroring.

As a side note, let does not allow you to declare a variable with a name that already exists in the current scope. This is why if any of your if statements are true an error would be thrown, because days was already declared at the top (you could also assign if you want it to have a default value). You’d want to declare it at the top before the if statement and then assign it in the if statements with just days = x;

1 Like

I just realized something too; I can’t declare it as a constant because then I’ll get an error when it tries to change the days value.

1 Like