Check for false

前端 未结 6 2001
孤城傲影
孤城傲影 2021-02-05 02:43

Is there any better way of doing this?

if(borrar() !== false)
{
    alert(\'tatatata bum bum bum prapra\');
}
return false;
6条回答
  •  感情败类
    2021-02-05 03:07

    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
    

提交回复
热议问题