Understanding JavaScript Truthy and Falsy

后端 未结 7 1884
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2020-11-22 08:48

    FALSY

    • false
    • 0 (zero)
    • "", '', `` (empty strings)
    • null
    • undefined
    • NaN (not a number)

    note : Empty array ([]) is not falsy

    TRUTHY

    • Everything that is not FALSY
    0 讨论(0)
  • 2020-11-22 08:52

    From my understanding, I believe that var a = 1; is the only truthy and the rest are falsy’s - is this correct?

    No.

    1. var a = 0;

      Number zero is falsy. However, note that the string zero "0" is truthy.

    2. var a = 10 == 5;

      This is same as var a = (10 == 5);, so this is falsy.

    3. var a = 1;

      var a = -1;

      Any non-zero number including negative numbers is truthy.

    Quoting from MDN

    In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

    List of falsy values in JavaScript:From MDN

    1. false
    2. null
    3. undefined
    4. 0
    5. NaN
    6. '', "", ``(Empty template string)
    7. document.all
    8. 0n: BigInt
    9. -0
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-11-22 09:00

    Truthy -> Value that resolve to true in boolean context

    Falsy -> Value that resolve to false in boolean context


    For better understanding, falsy values is given below.

    1. false
    2. 0
    3. empty string
    4. null
    5. undefined
    6. NaN
    0 讨论(0)
提交回复
热议问题