Skip to content

Instantly share code, notes, and snippets.

@susanBuck
Created September 26, 2025 15:24
Show Gist options
  • Select an option

  • Save susanBuck/8d4066d108fcb31fe8d361702e189c28 to your computer and use it in GitHub Desktop.

Select an option

Save susanBuck/8d4066d108fcb31fe8d361702e189c28 to your computer and use it in GitHub Desktop.
variable scope example
// For the purposes of this demo, hard-code answer and response
let answer = 4;
let response = 'e';
// THE FOLLOWING WILL *NOT* WORK
for (let i = 0; i < 3; i++) {
if (answer % 2 == 0 && response == 'e') {
let correct = true;
} else if (answer % 2 == 1 && response == '0') {
let correct = true;
} else {
let correct = false;
}
// Initializing `correct` within the if/else if/else block makes it only available
// within that block. Thus, when we try to access it in the following line, we get
// the error Uncaught ReferenceError: correct is not defined
console.log(correct);
}
// THE FOLLOWING WILL WORK
for (let i = 0; i < 3; i++) {
// To fix, we initialize correct as null *before* the if/else if/else block
let correct = null;
if (answer % 2 == 0 && response == 'e') {
correct = true;
} else if (answer % 2 == 1 && response == '0') {
correct = true;
} else {
correct = false;
}
// This now works
console.log(correct);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment