JavaScript checking for null vs. undefined and difference between == and ===

前端 未结 8 827
忘了有多久
忘了有多久 2020-11-22 16:53
  1. How do I check a variable if it\'s null or undefined and what is the difference between the null and undefined?<

8条回答
  •  孤独总比滥情好
    2020-11-22 17:19

    Ad 1. null is not an identifier for a property of the global object, like undefined can be

    let x;      // undefined
    let y=null; // null
    let z=3;    // has value
    // 'w'      // is undeclared
    
    if(!x) console.log('x is null or undefined');
    if(!y) console.log('y is null or undefined');
    if(!z) console.log('z is null or undefined');
    
    try { if(w) 0 } catch(e) { console.log('w is undeclared') }
    // typeof not throw exception for undelared variabels
    if(typeof w === 'undefined') console.log('w is undefined');

    Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):

    if

    == (its negation !=)

    === (its negation !==)

提交回复
热议问题