9

I've known null to be falsy. Then why does it act as if it is a truthy?

var status = null;

console.log('status:', status);

if(!!status) {
  console.log('status is truthy');   // it should not print
}

if(!!null) {
  console.log('null is truthy');   // it should not print
}
BlackBeard
  • 9,544
  • 7
  • 47
  • 59
noobie
  • 731
  • 4
  • 12
  • 32

2 Answers2

8

The issue is there is already a window.status, with which you conflict. It has setters that always make it a string, which causes your problems.

ASDFGerte
  • 4,015
  • 6
  • 14
  • 29
4

Change variable name status to something else (like status1) and the problem vanishes. This happens due to conflict with status object property of windows.

var status1 = null;


console.log('status1 -->', status1)

if(!!status1) {
  console.log('status')   // it should not print
}

if(!!null) {
  console.log('null')   // it should not print
}

NOTE: No matter what value you assign to window.status it'll get converted back to string. See this:

console.log(typeof window.status)

window.status = 4;   // type Number

console.log(typeof window.status) // still it remains string
BlackBeard
  • 9,544
  • 7
  • 47
  • 59