-3

I'm learning Javascript and I've gotten to conditionals. When I declare a variable 'sale' and assign it a value of true, my if statement runs, but if I reassign the value of sale to false, the code does not execute. Why is this happening?

let sale = true;

if (sale){
  console.log('Time to buy!');
}

The above code executes, but the following code doesn't and I don't understand why. I'm new to coding.

let sale = false;

if (sale = false){
  console.log('Enough inventory');
}
TheoM31
  • 3
  • 1
  • 1
    Because `=` is an [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment), not a [comparison operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality). You're setting sale to false (again) in your if statement, which returns the new value (false) so your condition evaluates to false. – ray Oct 19 '21 at 21:25

1 Answers1

0

The "=" statement in most programming languages is an assignment operator, it assigns values to certain variable names. What you are looking for is a "==" this checks if something is equal or not.

let sale = false;

if (sale == false){
  console.log('Enough inventory');
}
TheChicken4452
  • 93
  • 1
  • 10
  • 1
    In most cases, it's best to use `===` in place of `==` in JS due to `==` inherently converting the type: `'123' == 123` is true, whereas `'123' === 123` is false. – Bobby_Cheh Oct 19 '21 at 21:32