Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double pipes in JavaScript (||) throw error instead of evaluate as falsy

Tags:

I read that the double pipes in JavaScript check to see if a variable is falsy, and that undefined is a falsy value in JavaScript, e.g.

It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.

So I tried this out and find that undefined indeed does not get evaluated as falsy but instead throws an error:

let elemContent = document.getElementById('content');  let a = null; let b = 2;  elemContent.innerHTML += a || 'ok'; // "ok" elemContent.innerHTML += b || 'ok'; // "2" elemContent.innerHTML += whatever || 'ok'; // "ERROR: whatever is not defined" 

http://jsfiddle.net/ueqo6yko

Is undefined a falsy value in JavaScript or not, or how does one understand this contradiction?

like image 651
Edward Tanguay Avatar asked Sep 26 '17 10:09

Edward Tanguay


People also ask

What is considered Falsy in JavaScript?

A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context. JavaScript uses type conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops. The keyword false . The Number zero (so, also 0.0 , etc., and 0x0 ).

Which value is not Falsy in JavaScript?

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 .

Is 0 Falsy value in JS?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

Which of these values are Falsy?

The 7 falsy values are: 0 , 0n , null , undefined , false , NaN , and "" .


1 Answers

Because in your code, whatever is not only undefined but furthermore not declared

To avoid this error, you could do the following:

let elemContent = document.getElementById('content');  let a = null; let b = 2;  elemContent.innerHTML += a || 'ok'; // "ok" elemContent.innerHTML += b || 'ok'; // "2" elemContent.innerHTML += (typeof whatever !== 'undefined' && whatever) || 'ok3'; // "ok3" 
like image 157
laruiss Avatar answered Oct 21 '22 21:10

laruiss