Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this NULL variable truthy? [duplicate]

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
}
like image 422
noobie Avatar asked Jul 18 '18 12:07

noobie


People also ask

Is null a truthy value?

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .

Why is null == false false?

Answer : There no relative aspect between null and boolean. The value null is a literal (not a property of the global object like undefined can be). In APIs, null is often retrieved in place where an object can be expected but no object is relevant.

Why null === null is true?

2. How to check for null. missingObject === null evaluates to true because missingObject variable contains a null value. If the variable contains a non-null value, like an object, the expression existingObject === null evaluates to false .

Why null == undefined is true?

Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.


2 Answers

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.

like image 195
ASDFGerte Avatar answered Sep 22 '22 02:09

ASDFGerte


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
like image 26
BlackBeard Avatar answered Sep 22 '22 02:09

BlackBeard