0

I thought I can define a var in an if statement and use it later in the following code. Why is this not working in my example?

let a = prompt('1', '');


if (a == 1) {
  let x = 10;
  let y = 20;
  let z = x + y;
} else {
  let z = 50;
}

alert(z);

I'm pretty new to JS, thats why this error comes up for me.
What would be the correct way to override z if the if is false?

jona
  • 354
  • 4
  • 17
  • [MDN - let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) – Yousaf Apr 30 '21 at 10:01
  • It is because `z` is out of scope. If you want to use it outside `if`, you need to declare them out of `if` condition. – TechySharnav Apr 30 '21 at 10:01
  • `let` is block `{}` scoped ... – KcH Apr 30 '21 at 10:03
  • 1
    `let` (and `const`) have **block** scope. So each of your two `z` variables exists only within the block where you've declared it. To use one `z` throughout that code, declare it in the containing block: `let a = prompt('1', ''); let z; if (a == 1) { let x = 10; let y = 20; z = x + y; } else { z = 50; } alert(z);` (FWIW, I go into `let` and `const` in a fair bit of detail in Chapter 2 of my recent book *JavaScript: The New Toys*. Links in my profile if you're interested.) – T.J. Crowder Apr 30 '21 at 10:05

1 Answers1

1

It is because z is out of scope. If you want to use it outside if, you need to declare them out of if condition

let a = prompt('1', '');
let x, y, z;

if (a == 1) {
  x = 10;
  y = 20;
  z = x + y;
} else {
  z = 50;
}

alert(z);
TechySharnav
  • 4,869
  • 2
  • 11
  • 29