Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics Making Decisions in Your Code with Conditional Statements Boolean Values

karina037
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karina037
Full Stack JavaScript Techdegree Graduate 17,179 Points

How let was re-assigned?

Hi, can anyone explain me please how the second 'if' block was able to show re-assigned 'let', i.e. let correctGuess = true, from the first 'if' block?

I thought 'let' can be changed only within one block and outside that block it should always return the initial meaning (which was line1 let correctGuess = false). Is it something to do with 'if'?

let correctGuess = false;
const number = 6;
const guess = prompt("Guess a number between 1 and 10");

if (+guess === number) {
  correctGuess = true;
}

if (correctGuess) {
  console.log("Correct");
} else {
  console.log('Sorry not correct.');
}

1 Answer

Michael Cook
Michael Cook
2,125 Points

Hey Karina,

let does have block-level scoping, but your correctGuess variable is defined globally, so it actually has global scope. If you were to re-initialize correctGuess inside the if-statement though, then it would create a new variable inside that scope rather than reassign the variable at the top of your program. To demonstrate, try running this modified code:

// this is defined globally, so it is available anywhere in your program
let correctGuess = false;
const number = 6;
const guess = prompt("Guess a number between 1 and 10");

// code modified in this block
// run the code and see what difference this makes 
if (+guess === number) {
  let correctGuess = true;
}

if (correctGuess) {
  console.log("Correct");
} else {
  console.log('Sorry not correct.');
}

I hope this helps you. If you're still confused leave a comment and I'll try to clarify further :).