Comparison expression inside Promise always return true

Viewed 350

I'm learning about Promise in Javascript. But when I tried to write some lines of code, I have this problem. My "if" statement, which I declare inside a Promise Obj always return true. Here's information:

  • Environment: Chrome Dev Tools - Chrome Dev Tools - Chromium 64.0.3282.140
  • Code:

var status = false;
var promise = new Promise(function(resolve, reject) {
  if (status) {
    console.log("TRUE")
    resolve({
      value: 'true'
    });
  } else {
    console.log("FALSE");
    reject({
      value: 'false'
    });
  }
});

  • Expected output: FALSE
  • What happened instead: TRUE
  • Notice: whatever the value of "status" is, the output always true.
    I'm really looking for an explanation for my problem here. Thank you so much.
1 Answers

status is a predefined variable in browsers.

When you assign a value to it, it is cast to a string.

false becomes "false" which is a true value.

This is why you should avoid globals. Conflicts with other people's variables are never fun.


Wrap your code in an IIFE to avoid trying to create variables in the global scope.

(function() {

  var status = false;
  var promise = new Promise(function(resolve, reject) {
    if (status) {
      console.log("TRUE")
      resolve({
        value: 'true'
      });
    } else {
      console.log("FALSE");
      reject({
        value: 'false'
      });
    }
  });

}());

Related