Understanding JavaScript Truthy and Falsy

后端 未结 7 1961
深忆病人
深忆病人 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:38

    There's a simple way to check, which you can use now and forever:

    function truthyOrFalsy(a) {
        return a ? "truthy" : "falsy";
    }
    

    To wit:

    > truthyOrFalsy(0)
    "falsy"
    > truthyOrFalsy(10 == 5)
    "falsy"
    > truthyOrFalsy(1)
    "truthy"
    > truthyOrFalsy(-1)
    "truthy"
    

    Also see a list of all falsey values in JavaScript.

提交回复
热议问题