'Check for false
Is there any better way of doing this?
if(borrar() !== false)
{
alert('tatatata bum bum bum prapra');
}
return false;
Solution 1:[1]
If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.
Also, this is the same in a slightly smaller footprint:
if(borrar() !== !1)
Solution 2:[2]
You can use something simpler:
if(!var){
console.log('var is false');
}
Solution 3:[3]
If you want it to check explicit for it to not be false (boolean value) you have to use
if(borrar() !== false)
But in JavaScript we usually use falsy and truthy and you could use
if(!borrar())
but then values 0, '', null, undefined, null and NaN would not generate the alert.
The following values are always falsy:
false,
,0 (zero)
,'' or "" (empty string)
,null
,undefined
,NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)
Source: https://www.sitepoint.com/javascript-truthy-falsy/
As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:
!![] === true
!!'false' === true
!!false === false
!!undefined === false
Solution 4:[4]
Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.
if(!(borrar() === false))
or
if(borrar() === true)
Solution 5:[5]
Like this:
if(borrar())
{
// Do something
}
If borrar() returns true then do something (if it is not false).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | Peter Mortensen |
| Solution 3 | Peter Mortensen |
| Solution 4 | Peter Mortensen |
| Solution 5 | Peter Mortensen |
