Understanding JavaScript Truthy and Falsy

后端 未结 7 1957
深忆病人
深忆病人 2020-11-22 08:20

Can someone please explain JavaScript Truthy and Falsy, using the below sample data. I have read other threads but still confused.

var a = 0;

var a = 10 ==          


        
7条回答
  •  [愿得一人]
    2020-11-22 08:54

    In short there are only 6 types of falsy values: You can use this snippet to test them:

    function isTruthy(val){
        if(val){
            console.log(val + ' is Truthy');
        }else{
            console.log(val + ' is falsy');
        }
    }
        
    
    // all below are truthy
    isTruthy (true)
    isTruthy ({})
    isTruthy ([])
    isTruthy (42)
    isTruthy ("0")
    isTruthy ("false")
    isTruthy (new Date())
    isTruthy (-42)
    isTruthy (12n)
    isTruthy (3.14)
    isTruthy (-3.14)
    isTruthy (Infinity)
    isTruthy (-Infinity)
    
    //all below are falsy
    isTruthy(0);
    isTruthy("");
    isTruthy(false);
    isTruthy(NaN);
    isTruthy(null);
    isTruthy(undefined);
    

    Refer this site for details: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

提交回复
热议问题