Understanding JavaScript Truthy and Falsy

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

    Easy way to check Falsy Value and True value

    function truthyOrFalsy(val){
      if(val){
        console.log (`${val} is truthy`);
      } else{
        console.log (`${val} is falsy`);
      }   
    }
    

    Check all FALSY value:

    truthyOrFalsy(false);      //Output: false is falsy
    truthyOrFalsy(null);       //Output: null is falsy
    truthyOrFalsy(0);          //Output: 0 is falsy
    truthyOrFalsy('');         //Output:  is falsy  [blank refers to '']
    truthyOrFalsy(NaN);        //Output: NaN is falsy
    truthyOrFalsy(undefined);  //Output: undefined is falsy
    

    Please note that undefined is not explicitly used to set as value. Some common scenarios will create undefined:

    • Parameter defined in function but not passed argument in callback function.
    • If nothing returns in function
    • If accessing to an object property/method which is not defined
    • If accessing to an array element which is not defined
    function add(num1, num2){   
        console.log(num1, num2);    
    }
    const result = add(44);
    console.log(result);
    //Output: 44 undefined
    //        undefined
    
    const car = {color:"Blue", price: 200000};
    console.log(car.category);
    //Output: undefined
    arrColors = ["Blue", "Sky", "Purple"];
    console.log(arrColors[5]);
    //Output: undefined
    

    Check all TRUTHY values

    All values are truthy unless they are defined as falsy.

    Although ' ', '0', -1, [] could be enlisted to be checked.

    truthyOrFalsy(' ');      //Output: is truty     [blank refers to space inside 
                             //                       quote ]
    truthyOrFalsy('0');       //Output: 0 is truty 
    truthyOrFalsy([]);          //Output: is truty  [blank refers to an empty array]
    truthyOrFalsy(-1);         //Output: -1 is truty 
    

提交回复
热议问题