Mike3456 Posted March 28, 2016 Share Posted March 28, 2016 (edited) For "A == B" to be true the actual values of A and B have to be equal. In the comparison "null == undefined", both "null" and "undefined" are final values that are different syntactically. They are also different semantically, because for an object to be "null" it has to be explicitly defined as such, whereas for anything to be "undefined" it has to be declared without defining (meaning without initializing). Technically, a variable can be initialized and then set to "undefined" but this is the same as if never initialized. In other words, "null" and "undefined" are different values, both syntactically and semantically. Edited March 28, 2016 by Mike3456 Link to comment Share on other sites More sharing options...
Ingolme Posted March 28, 2016 Share Posted March 28, 2016 Javascript does a lot of type juggling when using the == comparison operator. Both null and undefined evaluate to false when evaluated as boolean. If you want to differentiate between null and undefined, use the === strict comparison operator, which also takes data types into account. Link to comment Share on other sites More sharing options...
davej Posted March 28, 2016 Share Posted March 28, 2016 This question seems vague to me. In Javascript 'null' is a value that can be assigned, but 'undefined' is the value of a variable that was never given a value. If typeof x == 'undefined' then the variable x was never declared. If x == 'undefined' then the variable x was declared but was never given a value. The == operator provides some type coercion while the === operator is a strict compare. <script> 'use strict'; window.onload = init; function init() { //var x; var y; var z = null; if (typeof x == 'undefined'){ alert('typeof x == "undefined" is true'); } if (typeof x === 'undefined'){ alert('typeof x === "undefined" is true'); } try{ alert('x = ' + x); }catch(e){ alert('Exception thrown: '+e.message); } } </script> ...I guess the question in the subject line is essentially a question about 'truthyness' https://developer.mozilla.org/en-US/docs/Glossary/Truthy ...because null and undefined are both 'falsy' values, but really who cares? This has little or no practical usefulness. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now