What is the difference between null and undefined in JavaScript?

前端 未结 30 3281
夕颜
夕颜 2020-11-21 23:06

I want to know what the difference is between null and undefined in JavaScript.

30条回答
  •  醉话见心
    2020-11-21 23:38

    Please read the following carefully. It shall remove all your doubts regarding the difference between null and undefined in JavaScript. Also you can use the utility function given below to exactly determine types.

    In JavaScript we can have following types of variables.

    1. Undeclared Variables
    2. Declared but Unassigned Variables
    3. Variables assigned with literal undefined
    4. Variables assigned with literal null
    5. Variables assigned with anything other than undefined or null

    Following explains each of these cases one by one

    1. Undeclared Variables: Following holds true for undeclared variables

      • Can only be checked by typeof() which returns string 'undefined'
      • Cannot be checked with == or === or by if or conditional operator ? (throws Reference Error)
    2. Declared but Unassigned Variables

      • typeof returns string 'undefined'
      • == check with null returns true
      • == check with undefined returns true
      • === check with null returns false
      • === check with undefined returns true
      • if or conditional operator ? returns false
    3. Variables assigned with literal undefined: These variables are treated similarly as the Declared But Unassigned Variables.

    4. Variables assigned with literal null

      • typeof returns string 'object'
      • == check with null returns true
      • == check with undefined returns true
      • === check with null returns true
      • === check with undefined returns false
      • if or conditional operator ? returns false
    5. Variables assigned with anything other than undefined or null

      • typeof returns one of the following strings: 'string','number','boolean','function', 'object','symbol'

    Following provides the algorithm for correct type checking of a variable:

    1. Check for undeclared/unassigned/assigned with undefined using typeof. return if string 'undefined' is returned.
    2. Check for null using ===. return 'null' if true.
    3. Check for actual type using typeof. return type if not equal to 'object'
    4. Call Object.prototype.toString.call(o) to determine actual object type. It shall return a string of type '[object ObjectType]' for all the built in Javascript or DOM defined Objects. For user defined objects it returns '[object Object]'

    You can also use the following utility function for determining types. It currently supports all ECMA 262 2017 types.

    function TypeOf(o,bReturnConstructor)
     {
       if(typeof o==='undefined') return 'undefined'
       if(o===null) return 'null'   
       if(typeof o!=='object') return typeof o
    
       var type=Object.prototype.toString.call(o)
      switch(type)
      {
         //Value types:4
         case '[object Number]': type='number';break;
         case '[object String]': type='string';break;
         case '[object Boolean]': type='boolean';break;
         case '[object Date]': type='date';break;
    
    
       //Error Types:7
         case '[object Error]': type='error';break;
         case '[object EvalError]': type='evalerror';break;
         case '[object RangeError]': type='rangeerror';break;
         case '[object ReferenceError]': type='referenceerror';break;
         case '[object SyntaxError]': type='syntaxerror';break;
         case '[object TypeError]': type='typeerror';break;
         case '[object URIError]': type='urierror';break;
    
    
        //Indexed Collection and Helper Types:13
         case '[object Array]': type='array';break;
         case '[object Int8Array]': type='int8array';break;
         case '[object Uint8Array]': type='uint8array';break;
         case '[object Uint8ClampedArray]': type='uint8clampedarray';break;
         case '[object Int16Array]': type='int16array';break;
         case '[object Uint16Array]': type='uint16array';break;
         case '[object Int32Array]': type='int32array';break;
         case '[object Uint32Array]': type='uint32array';break;
         case '[object Float32Array]': type='float32array';break;
         case '[object Float64Array]': type='float64array';break;
         case '[object ArrayBuffer]': type='arraybuffer';break;
         case '[object SharedArrayBuffer]': type='sharedarraybuffer';break;
         case '[object DataView]': type='dataview';break;
    
        //Keyed Collection Types:2
         case '[object Map]': type='map';break;
         case '[object WeakMap]': type='weakmap';break;
    
        //Set Types:2
         case '[object Set]': type='set';break;
         case '[object WeakSet]': type='weakset';break;
    
        //Operation Types
        case '[object RegExp]': type='regexp';break;
        case '[object Proxy]': type='proxy';break;
        case '[object Promise]': type='promise';break;
    
        case '[object Object]': type='object';
                 if(bReturnConstructor && o.constructor) type=o.constructor.toString().match(/^function\s*([^\s(]+)/)[1];
             break;
        default:
            type=type.split(' ')[1]
            type=type.substr(0,type.length-1)   
    
       }
        return type 
    }
    

提交回复
热议问题