Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

karina037
seal-mask
.a{fill-rule:evenodd;}techdegree
karina037
Full Stack JavaScript Techdegree Student 8,680 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
425 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 :).