What is the difference between null and undefined in JavaScript?

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

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

30条回答
  •  旧巷少年郎
    2020-11-21 23:53

    Check this out. The output is worth thousand words.

    var b1 = document.getElementById("b1");
    
    checkif("1, no argument"                        );
    checkif("2, undefined explicitly",     undefined);
    checkif("3, null explicitly",               null);
    checkif("4, the 0",                            0);
    checkif("5, empty string",                    '');
    checkif("6, string",                    "string");
    checkif("7, number",                      123456);
    
    function checkif (a1, a2) {
    	print("\ncheckif(), " + a1 + ":");
    	if (a2 == undefined) {
    		print("==undefined:    YES");
    	} else {
    		print("==undefined:    NO");
    	}
    	if (a2 === undefined) {
    		print("===undefined:   YES");
    	} else {
    		print("===undefined:   NO");
    	}
    	if (a2 == null) {
    		print("==null:         YES");
    	} else {
    		print("==null:         NO");
    	}
    	if (a2 === null) {
    		print("===null:        YES");
    	} else {
    		print("===null:        NO");
    	}
    	if (a2 == '') {
    		print("=='':           YES");
    	} else {
    		print("=='':           NO");
    	}
    	if (a2 === '') {
    		print("==='':          YES");
    	} else {
    		print("==='':          NO");
    	}
    	if (isNaN(a2)) {
    		print("isNaN():        YES");
    	} else {
    		print("isNaN():        NO");
    	}
    	if (a2) {
    		print("if-?:           YES");
    	} else {
    		print("if-?:           NO");
    	}
    		print("typeof():       " + typeof(a2));
    }
    
    function print(v) {
    	b1.innerHTML += v + "\n";
    }
    
    
    
    
    
    
    

    See also:

    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

    Cheers!

提交回复
热议问题