Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if falsy except zero in JavaScript

I am checking if a value is not falsy with

if (value) {   .. } 

but I do want to accept zeros as a (non-falsy) value. How is this normally done? Would it be

if (value || value === 0) {   .. } 

or what?

like image 952
mortensen Avatar asked Jul 25 '15 13:07

mortensen


People also ask

Is zero considered Falsy in JavaScript?

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.

How do you know if a value is not zero?

Use the strict inequality operator to check if a value is not equal to 0 , e.g. myVar !== 0 . The strict inequality operator checks if two values are not equal and returns a boolean result - true if they aren't equal, and false otherwise.

Is 0 Falsy in TypeScript?

These are the following falsy values in TypeScript and JavaScript: 0. false.


2 Answers

if (value || value === 0) {   .. } 

is cleaner way, no problem.

Just for fun try this

val = 0; if(val){ console.log(val) } //outputs 0   **update - it used to be.. but now it seems it doesnt in chrome 

And

var val = 0; if(val){ console.log(val) } //outputs nothing 
like image 90
vinayakj Avatar answered Sep 29 '22 14:09

vinayakj


I would use value || value === 0. It's fine whichever way you do it but IMO this is the cleanest option.

like image 29
RK. Avatar answered Sep 29 '22 14:09

RK.