Help with my "if/else" code

Could someone help me to understand what I’m doing wrong in this code:

let generateTarget = Math.floor(Math.random() * 10);
let humanGuess = Math.floor(Math.random() * 10);
let compGuess = Math.floor(Math.random() * 10);

console.log('Target is: ' + generateTarget);
console.log('Human is: ' + humanGuess);
console.log('Computer is: ' + compGuess);

//Determine compDifference
if (compGuess > generateTarget) {
    let compDifference = (compGuess - generateTarget);
  } else (generateTarget >= compGuess) {
    let compDifference = (generateTarget - compGuess);
  } 

//Determine humanDifference
if (humanGuess > generateTarget) {
  let humanDifference = (humanGuess - generateTarget);
} else if (generateTarget >= humanGuess) {
  let humanDifference = (generateTarget - humanGuess);
}

//Determine winner
  if (compDifference > humanDifference) {
    console.log('You won');
  } else if (humanDifference > compDifference) {
    console.log('You lost');
  } else {console.log('It was a tie');
         }

I’m sure there are better ways of doing this, but this method is the only one I currently understand, so I’m just trying to figure out why this isn’t working. Thanks

What are the errors you are seeing? What are the different things you have tried to solve the problem?

1 Like

@ArielLeslie I have been writing in Codepen so it never offers me any feedback. I did try it in Firefox Web Dev.

There it says “SyntaxError: unexpected token: ‘{’ debugger eval code:12:39”. But it doesn’t say where the erroneous { is. I looked but I don’t see where I’m misusing a {.

I commented out the “if/else” sections to confirm that the first section works, so I know the problem exists in the “if/else” sections.

Hello!

Here is a problem:

//Determine humanDifference
if (humanGuess > generateTarget) {
  let humanDifference = (humanGuess - generateTarget);
} else if (generateTarget >= humanGuess) {
  let humanDifference = (generateTarget - humanGuess);
}

The syntax is wrong if You compare it to Your other if…else:

if (condition)
else if (condition)
else // The else never has a condition; the else is executed when the other conditions are not met.

Besides that, the variables humanDifference and compDifference are declared in a different context, thus will be undefined when You try to access their values.

1 Like

Actually, it does. It’s online 12, position 39.
It’s this line:

  } else (generateTarget >= compGuess) {
2 Likes

@skaparate Thanks!

I see my error in the if…else syntax and corrected that.

How can I make the values for humanDifference and compDifference accessible?

Hmmm, do You understand the concept of context and scope?

Whenever You use the { and } You’re creating a new context (this is an oversimplification, by the way). That means, everything that’s inside them is not accessible from the outer context, although it is from an inner context. Maybe You should read how do scopes and contexts work on JS. Take a look at a visual representation of the context.

If, after reading about contexts and scopes in JS, You still can’t find where the problem lies, then I’ll give the answer and another explanation :slight_smile:.

1 Like

Thanks I will read those and hopefully I understand it then!

1 Like

@ArielLeslie Thanks now I know what the eval code:12:39 means!

Glad I could help. That little piece of information isn’t always 100% reliable, but it super helpful. Happy coding!

1 Like

@skaparate I did read the article and looked at the visual representations. I understand from the article that let and const are “block scope local variables” and thus aren’t accessible outside the block (though to be honest, that was pretty much the only thing I understood in the article).

I guess my use of the let is occurring within a function, which I wasn’t aware of. In fact, I was writing the code this way to try to not use (what I understood to be) functions to allow values to be globally accessible.

The visual representations were totally lost on me, in part because the concept of this was totally new.

The whole experience makes me wonder if I’m delving into areas I’m not fully prepared for (as every explanation I read involves concepts I’m unfamiliar with (don’t get me wrong- I don’t mind that feeling- it’s natural and I’m familiar with it, having learned a couple of spoken languages as an adult)). I was following a different curriculum for JS but I think I will start at the beginning of FCCs JS curriculum (I did their HTML/CSS cert.) Maybe once I work through that, I’ll be better prepared to understand the explanations of the things confusing me right now.

Of course, I can work on multiple things at once! So in the meantime, to close this loop, if you have any further explanations (or an answer!) to how I can make the let variables globally accessible, I’m all eyes! I appreciate it!

Hmmm, yes, maybe it was more confusing than helping, sorry :sweat_smile:.

In the meantime, think of a context like everything between an opening { and a closing } bracket is a different context, thus inaccessible from outside the brackets. Forget about the this keyword for now (there are other contexts and, yes, it may be complicated).

Now, for the answer, you just have to move the let humanDifference and let compDifference to the start of the script without assigning a value. Then, inside their respective ifs assign the value you’re calculating:

// Assume this is the start of the script (do the same for humanDifference):
let compDifference;

if (compGuess > generateTarget) {
  compDifference = (compGuess - generateTarget);
} else (generateTarget >= compGuess) {
  compDifference = (generateTarget - compGuess);
}

// Now compDifference is accessible to every other context on the same file.

To make it easy I said move it to the start of the file/script, but the real requirement is to declare it before use, which means just before assigning a value, just before a new context (i.e. if…else, switch…case, while, for loops…), etc.

1 Like

Thank you!!! I think I understand the importance of declaring them before use. I’ll mess around with that.

Don’t worry about the article being confusing. I expect to be confused for quite a while! That’s a sign I’m learning things.

I appreciate the help!

1 Like

@skaparate I made your corrections and it worked; thanks again. I had just one other question. I am now following the FCC curriculum and in the lesson on Global Scope and Functions, the author writes " Variables which are used without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var .

I understood the limits of the accessibility of my let variables because they existed within my if sections, given your feedback. But the explanation above seems to imply that that shouldn’t be the case?

Also, (and not to open a can of worms), but I had heard var had “fallen out of favor”? (of course, I don’t yet personally understand the reasons why because I’m a beginner) But anyway, I was surprised by that.

Without var just means you let the runtime do it for you (bad idea). In the browser, the variable will end up on the global window object.

inGlobal = 'I really should not be here'
window.inGlobal
// "I really should not be here"

Once a variable is global it is accessible from anywhere.

The challenge in question is not talking about using let or const instead of var, it is talking about not using any declaration at all and what happens.

2 Likes

You need some context first.

EcmaScript (ES) is the standard that most JavaScript implementations use (sometimes they add non-standard features). Until ES5, the only way to declare and define variables was using the keyword var. ES6 introduced the let and const keywords, which are also used to declare variables.

What the author meant is that not using let, const or var to declare a variable means that the variable is declared on the global scope (window on the browser).

I think is a matter of taste. let and const are more strict, which I personally like because it helps you to find errors earlier, while var is more “loose” and has a weird “sense” of context xD. Look at this:

var aBoolean = true;

if (aBoolean) {
  var aText = 'This is true';
} else {
  var aText = 'This is not true';
}

console.log('aText:', aText)
// Output: This is true

That’s weird for me xD.

My first language was Java, which is strongly typed. In Java, if I define a variable inside a context, that variable is not accessible to any outer (or parent) context (only to sub/child contexts). Using let and const get me closer to what I’m used to.

Search on internet about the var keyword, You may like it or not :slight_smile:.

1 Like