<p>How do I check if an object property in JavaScript is undefined?</p>

[{'answer_id': 27510, 'author': 'tslocum', 'author_id': 1662, 'author_profile': 'https://Stackoverflow.com/users/1662', 'pm_score': -1, 'selected': False, 'text': '<pre><code>if (somevariable == undefined) {\n  alert(\'the variable is not defined!\');\n}\n</code></pre>\n\n<p>You can also make it into a function, as shown <a href="http://verens.com/archives/2005/07/25/isset-for-javascript/" rel="nofollow noreferrer">here</a>:</p>\n\n<pre><code>function isset(varname){\n  return(typeof(window[varname]) != \'undefined\');\n}\n</code></pre>\n'}, {'answer_id': 27517, 'author': 'Pandincus', 'author_id': 2273, 'author_profile': 'https://Stackoverflow.com/users/2273', 'pm_score': 7, 'selected': False, 'text': '<p>In JavaScript there is <strong>null</strong> and there is <strong>undefined</strong>.  They have different meanings.</p>\n<ul>\n<li><strong>undefined</strong> means that the variable value has not been defined; it is not known what the value is.</li>\n<li><strong>null</strong> means that the variable value is defined and set to null (has no value).</li>\n</ul>\n<p>Marijn Haverbeke states, in his free, online book &quot;<a href="http://eloquentjavascript.net/" rel="noreferrer">Eloquent JavaScript</a>&quot; (emphasis mine):</p>\n<blockquote>\n<p>There is also a similar value, null, whose meaning is \'this value is defined, but it does not have a value\'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. <strong>In practical programs, it is often necessary to check whether something \'has a value\'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.</strong></p>\n</blockquote>\n<p>So, I guess the best way to check if something was undefined would be:</p>\n<pre><code>if (something == undefined)\n</code></pre>\n<p>Object properties should work the same way.</p>\n<pre><code>var person = {\n    name: &quot;John&quot;,\n    age: 28,\n    sex: &quot;male&quot;\n};\n\nalert(person.name); // &quot;John&quot;\nalert(person.fakeVariable); // undefined\n</code></pre>\n'}, {'answer_id': 27911, 'author': 'Ricky', 'author_id': 653, 'author_profile': 'https://Stackoverflow.com/users/653', 'pm_score': 4, 'selected': False, 'text': '<p>The solution is incorrect. In JavaScript,</p>\n\n<pre><code>null == undefined\n</code></pre>\n\n<p>will return true, because they both are "casted" to a boolean and are false. The correct way would be to check</p>\n\n<pre><code>if (something === undefined)\n</code></pre>\n\n<p>which is the identity operator...</p>\n'}, {'answer_id': 416327, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 13, 'selected': True, 'text': '<p>The usual way to check if the value of a property is the special value <code>undefined</code>, is:</p>\n<pre class="lang-js prettyprint-override"><code>if(o.myProperty === undefined) {\n  alert(&quot;myProperty value is the special value `undefined`&quot;);\n}\n</code></pre>\n<p>To check if an object does not actually have such a property, and will therefore return <code>undefined</code> by default when you try to access it:</p>\n<pre class="lang-js prettyprint-override"><code>if(!o.hasOwnProperty(\'myProperty\')) {\n  alert(&quot;myProperty does not exist&quot;);\n}\n</code></pre>\n<p>To check if the value associated with an identifier is the special value <code>undefined</code>, <em>or</em> if that identifier has not been declared:</p>\n<pre class="lang-js prettyprint-override"><code>if(typeof myVariable === \'undefined\') {\n  alert(\'myVariable is either the special value `undefined`, or it has not been declared\');\n}\n</code></pre>\n<p>Note: this last method is the only way to refer to an <strong>undeclared</strong> identifier without an early error, which is different from having a value of <code>undefined</code>.</p>\n<p>In versions of JavaScript prior to ECMAScript 5, the property named &quot;undefined&quot; on the global object was writeable, and therefore a simple check <code>foo === undefined</code> might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.</p>\n<p>However, in modern JavaScript, &quot;undefined&quot; is not a keyword, and so variables inside functions can be named &quot;undefined&quot; and shadow the global property.</p>\n<p>If you are worried about this (unlikely) edge case, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void" rel="noreferrer">the void operator</a> to get at the special <code>undefined</code> value itself:</p>\n<pre class="lang-js prettyprint-override"><code>if(myVariable === void 0) {\n  alert(&quot;myVariable is the special value `undefined`&quot;);\n}\n</code></pre>\n'}, {'answer_id': 3232194, 'author': 'Rixius', 'author_id': 212307, 'author_profile': 'https://Stackoverflow.com/users/212307', 'pm_score': 2, 'selected': False, 'text': "<pre><code>function isUnset(inp) {\n  return (typeof inp === 'undefined')\n}\n</code></pre>\n\n<p>Returns false if variable is set, and true if is undefined.</p>\n\n<p>Then use:</p>\n\n<pre><code>if (isUnset(var)) {\n  // initialize variable here\n}\n</code></pre>\n"}, {'answer_id': 3345556, 'author': 'Kevin', 'author_id': 403606, 'author_profile': 'https://Stackoverflow.com/users/403606', 'pm_score': 6, 'selected': False, 'text': '<pre><code>if ( typeof( something ) == "undefined") \n</code></pre>\n\n<p>This worked for me while the others didn\'t.</p>\n'}, {'answer_id': 3550319, 'author': 'MarkPflug', 'author_id': 190371, 'author_profile': 'https://Stackoverflow.com/users/190371', 'pm_score': 10, 'selected': False, 'text': '<p>I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is <strong>not</strong> a keyword in JavaScript and can in fact have a value assigned to it.</p>\n\n<h1>Correct Code</h1>\n\n<p>The most robust way to perform this test is:</p>\n\n<pre><code>if (typeof myVar === "undefined")\n</code></pre>\n\n<p>This will always return the correct result, and even handles the situation where <code>myVar</code> is not declared.</p>\n\n<h1>Degenerate code. DO NOT USE.</h1>\n\n<pre><code>var undefined = false;  // Shockingly, this is completely legal!\nif (myVar === undefined) {\n    alert("You have been misled. Run away!");\n}\n</code></pre>\n\n<p>Additionally, <code>myVar === undefined</code> will raise an error in the situation where myVar is undeclared.</p>\n'}, {'answer_id': 3770178, 'author': 'Eric', 'author_id': 455129, 'author_profile': 'https://Stackoverflow.com/users/455129', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m not sure where the origin of using <code>===</code> with <code>typeof</code> came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you also want to type check it too?</p>\n\n<pre><code>typeof x;                      // some string literal "string", "object", "undefined"\nif (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal\nif (typeof x == "string") {    // sufficient\n</code></pre>\n'}, {'answer_id': 6274093, 'author': 'Michael Anderson', 'author_id': 221955, 'author_profile': 'https://Stackoverflow.com/users/221955', 'pm_score': 6, 'selected': False, 'text': '<p>The issue boils down to three cases:</p>\n\n<ol>\n<li>The object has the property and its value is not <code>undefined</code>.</li>\n<li>The object has the property and its value is <code>undefined</code>.</li>\n<li>The object does not have the property.</li>\n</ol>\n\n<p>This tells us something I consider important:</p>\n\n<p><strong>There is a difference between an undefined member and a defined member with an undefined value.</strong></p>\n\n<p>But unhappily <code>typeof obj.foo</code> does not tell us which of the three cases we have. However we can combine this with <code>"foo" in obj</code> to distinguish the cases.</p>\n\n<pre><code>                               |  typeof obj.x === \'undefined\' | !("x" in obj)\n1.                     { x:1 } |  false                        | false\n2.    { x : (function(){})() } |  true                         | false\n3.                          {} |  true                         | true\n</code></pre>\n\n<p>Its worth noting that these tests are the same for <code>null</code> entries too</p>\n\n<pre><code>                               |  typeof obj.x === \'undefined\' | !("x" in obj)\n                    { x:null } |  false                        | false\n</code></pre>\n\n<p>I\'d argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value.</p>\n\n<p>For example: I\'ve just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.</p>\n\n<pre><code>if( typeof blob.x != \'undefined\' ) {  fn(blob.x); }\n</code></pre>\n\n<p>Which was clearer when written without a check for undefined.</p>\n\n<pre><code>if( "x" in blob ) { fn(blob.x); }\n</code></pre>\n\n<p>But as has been mentioned these are not exactly the same (but are more than good enough for my needs). </p>\n'}, {'answer_id': 7041744, 'author': 'Codebeat', 'author_id': 565244, 'author_profile': 'https://Stackoverflow.com/users/565244', 'pm_score': 4, 'selected': False, 'text': "<p>If you do</p>\n\n<pre><code>if (myvar == undefined )\n{ \n    alert('var does not exists or is not initialized');\n}\n</code></pre>\n\n<p>it will fail when the variable <code>myvar</code> does not exists, because myvar is not defined, so the script is broken and the test has no effect.</p>\n\n<p>Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.</p>\n\n<p>For example:</p>\n\n<pre><code>var myvar = 'test';\n</code></pre>\n\n<p>The global variable <em>myvar</em> is the same as <em>window.myvar</em> or <em>window['myvar']</em></p>\n\n<p>To avoid errors to test when a global variable exists, you better use:</p>\n\n<pre><code>if(window.myvar == undefined )\n{ \n    alert('var does not exists or is not initialized');\n}\n</code></pre>\n\n<p>The question if a variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its type or rely on <code>!window.myvar</code> to check if it has a proper/valid value. So even when the variable is not defined then <code>!window.myvar</code> is the same for <code>myvar = undefined</code> or <code>myvar = false</code> or <code>myvar = 0</code>.</p>\n\n<p>When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:</p>\n\n<pre><code>if( !window.myvar || typeof window.myvar != 'string' )\n{\n    alert('var does not exists or is not type of string');\n}\n</code></pre>\n\n<p>When the first and simple condition is true, the interpreter skips the next tests. </p>\n\n<p>It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable and is a better way of programming.  </p>\n\n<p>(y)</p>\n"}, {'answer_id': 7793028, 'author': 'Anoop', 'author_id': 460942, 'author_profile': 'https://Stackoverflow.com/users/460942', 'pm_score': 3, 'selected': False, 'text': '<p>You can get an array all undefined with path using the following code.</p>\n\n<pre><code> function getAllUndefined(object) {\n\n        function convertPath(arr, key) {\n            var path = "";\n            for (var i = 1; i &lt; arr.length; i++) {\n\n                path += arr[i] + "-&gt;";\n            }\n            path += key;\n            return path;\n        }\n\n\n        var stack = [];\n        var saveUndefined= [];\n        function getUndefiend(obj, key) {\n\n            var t = typeof obj;\n            switch (t) {\n                case "object":\n                    if (t === null) {\n                        return false;\n                    }\n                    break;\n                case "string":\n                case "number":\n                case "boolean":\n                case "null":\n                    return false;\n                default:\n                    return true;\n            }\n            stack.push(key);\n            for (k in obj) {\n                if (obj.hasOwnProperty(k)) {\n                    v = getUndefiend(obj[k], k);\n                    if (v) {\n                        saveUndefined.push(convertPath(stack, k));\n                    }\n                }\n            }\n            stack.pop();\n\n        }\n\n        getUndefiend({\n            "": object\n        }, "");\n        return saveUndefined;\n    }\n</code></pre>\n\n<p><a href="http://jsfiddle.net/anoop26667/9XbEK/" rel="noreferrer">jsFiddle</a> link</p>\n'}, {'answer_id': 9342877, 'author': 'Corey Richardson', 'author_id': 1419479, 'author_profile': 'https://Stackoverflow.com/users/1419479', 'pm_score': -1, 'selected': False, 'text': "<p><code>Object.hasOwnProperty(o, 'propertyname');</code></p>\n\n<p>This doesn't look up through the prototype chain, however.</p>\n"}, {'answer_id': 12589152, 'author': 'Joe Johnson', 'author_id': 836474, 'author_profile': 'https://Stackoverflow.com/users/836474', 'pm_score': 5, 'selected': False, 'text': '<p>I didn\'t see (hope I didn\'t miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):</p>\n<pre><code>if (obj &amp;&amp; obj.prop) {\n  // Do something;\n}\n</code></pre>\n<p>If the obj or obj.prop is undefined, null, or &quot;falsy&quot;, the if statement will not execute the code block. This is <em>usually</em> the desired behavior in most code block statements (in JavaScript).</p>\n<h2>UPDATE: (7/2/2021)</h2>\n<p>The latest version of JavaScript introduces a new operator for\noptional chaining: <code>?.</code></p>\n<p>This is probably going to be the most explicit and efficient method of checking for the existence of object properties, moving forward.</p>\n<p>Ref: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n'}, {'answer_id': 14306293, 'author': 'drzaus', 'author_id': 1037948, 'author_profile': 'https://Stackoverflow.com/users/1037948', 'pm_score': 5, 'selected': False, 'text': '<p>Crossposting <a href="https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript/14305002#14305002">my answer</a> from related question <em><a href="https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript">How can I check for &quot;undefined&quot; in JavaScript?</a></em>.</p>\n<p><em>Specific to this question, see test cases with <code>someObject.&lt;whatever&gt;</code>.</em></p>\n<hr />\n<p>Some scenarios illustrating the results of the various answers:\n<a href="http://jsfiddle.net/drzaus/UVjM4/" rel="nofollow noreferrer">http://jsfiddle.net/drzaus/UVjM4/</a></p>\n<p><em>(Note that the use of <code>var</code> for <code>in</code> tests make a difference when in a scoped wrapper)</em></p>\n<p>Code for reference:</p>\n<pre><code>(function(undefined) {\n    var definedButNotInitialized;\n    definedAndInitialized = 3;\n    someObject = {\n        firstProp: &quot;1&quot;\n        , secondProp: false\n        // , undefinedProp not defined\n    }\n    // var notDefined;\n\n    var tests = [\n        \'definedButNotInitialized in window\',\n        \'definedAndInitialized in window\',\n        \'someObject.firstProp in window\',\n        \'someObject.secondProp in window\',\n        \'someObject.undefinedProp in window\',\n        \'notDefined in window\',\n\n        \'&quot;definedButNotInitialized&quot; in window\',\n        \'&quot;definedAndInitialized&quot; in window\',\n        \'&quot;someObject.firstProp&quot; in window\',\n        \'&quot;someObject.secondProp&quot; in window\',\n        \'&quot;someObject.undefinedProp&quot; in window\',\n        \'&quot;notDefined&quot; in window\',\n\n        \'typeof definedButNotInitialized == &quot;undefined&quot;\',\n        \'typeof definedButNotInitialized === typeof undefined\',\n        \'definedButNotInitialized === undefined\',\n        \'! definedButNotInitialized\',\n        \'!! definedButNotInitialized\',\n\n        \'typeof definedAndInitialized == &quot;undefined&quot;\',\n        \'typeof definedAndInitialized === typeof undefined\',\n        \'definedAndInitialized === undefined\',\n        \'! definedAndInitialized\',\n        \'!! definedAndInitialized\',\n\n        \'typeof someObject.firstProp == &quot;undefined&quot;\',\n        \'typeof someObject.firstProp === typeof undefined\',\n        \'someObject.firstProp === undefined\',\n        \'! someObject.firstProp\',\n        \'!! someObject.firstProp\',\n\n        \'typeof someObject.secondProp == &quot;undefined&quot;\',\n        \'typeof someObject.secondProp === typeof undefined\',\n        \'someObject.secondProp === undefined\',\n        \'! someObject.secondProp\',\n        \'!! someObject.secondProp\',\n\n        \'typeof someObject.undefinedProp == &quot;undefined&quot;\',\n        \'typeof someObject.undefinedProp === typeof undefined\',\n        \'someObject.undefinedProp === undefined\',\n        \'! someObject.undefinedProp\',\n        \'!! someObject.undefinedProp\',\n\n        \'typeof notDefined == &quot;undefined&quot;\',\n        \'typeof notDefined === typeof undefined\',\n        \'notDefined === undefined\',\n        \'! notDefined\',\n        \'!! notDefined\'\n    ];\n\n    var output = document.getElementById(\'results\');\n    var result = \'\';\n    for(var t in tests) {\n        if( !tests.hasOwnProperty(t) ) continue; // bleh\n\n        try {\n            result = eval(tests[t]);\n        } catch(ex) {\n            result = \'Exception--\' + ex;\n        }\n        console.log(tests[t], result);\n        output.innerHTML += &quot;\\n&quot; + tests[t] + &quot;: &quot; + result;\n    }\n})();\n</code></pre>\n<p>And results:</p>\n<pre><code>definedButNotInitialized in window: true\ndefinedAndInitialized in window: false\nsomeObject.firstProp in window: false\nsomeObject.secondProp in window: false\nsomeObject.undefinedProp in window: true\nnotDefined in window: Exception--ReferenceError: notDefined is not defined\n&quot;definedButNotInitialized&quot; in window: false\n&quot;definedAndInitialized&quot; in window: true\n&quot;someObject.firstProp&quot; in window: false\n&quot;someObject.secondProp&quot; in window: false\n&quot;someObject.undefinedProp&quot; in window: false\n&quot;notDefined&quot; in window: false\ntypeof definedButNotInitialized == &quot;undefined&quot;: true\ntypeof definedButNotInitialized === typeof undefined: true\ndefinedButNotInitialized === undefined: true\n! definedButNotInitialized: true\n!! definedButNotInitialized: false\ntypeof definedAndInitialized == &quot;undefined&quot;: false\ntypeof definedAndInitialized === typeof undefined: false\ndefinedAndInitialized === undefined: false\n! definedAndInitialized: false\n!! definedAndInitialized: true\ntypeof someObject.firstProp == &quot;undefined&quot;: false\ntypeof someObject.firstProp === typeof undefined: false\nsomeObject.firstProp === undefined: false\n! someObject.firstProp: false\n!! someObject.firstProp: true\ntypeof someObject.secondProp == &quot;undefined&quot;: false\ntypeof someObject.secondProp === typeof undefined: false\nsomeObject.secondProp === undefined: false\n! someObject.secondProp: true\n!! someObject.secondProp: false\ntypeof someObject.undefinedProp == &quot;undefined&quot;: true\ntypeof someObject.undefinedProp === typeof undefined: true\nsomeObject.undefinedProp === undefined: true\n! someObject.undefinedProp: true\n!! someObject.undefinedProp: false\ntypeof notDefined == &quot;undefined&quot;: true\ntypeof notDefined === typeof undefined: true\nnotDefined === undefined: Exception--ReferenceError: notDefined is not defined\n! notDefined: Exception--ReferenceError: notDefined is not defined\n!! notDefined: Exception--ReferenceError: notDefined is not defined\n</code></pre>\n'}, {'answer_id': 18135509, 'author': 'Konstantin Smolyanin', 'author_id': 1823469, 'author_profile': 'https://Stackoverflow.com/users/1823469', 'pm_score': 7, 'selected': False, 'text': '<p>What does this mean: <strong>"undefined object property"</strong>?</p>\n\n<p>Actually it can mean two quite different things! First, it can mean <em>the property that has never been defined</em> in the object and, second, it can mean the <em>property that has an undefined value</em>. Let\'s look at this code:</p>\n\n<pre><code>var o = { a: undefined }\n</code></pre>\n\n<p>Is <code>o.a</code> undefined? Yes! Its value is undefined. Is <code>o.b</code> undefined? Sure! There is no property \'b\' at all! OK, see now how different approaches behave in both situations:</p>\n\n<pre><code>typeof o.a == \'undefined\' // true\ntypeof o.b == \'undefined\' // true\no.a === undefined // true\no.b === undefined // true\n\'a\' in o // true\n\'b\' in o // false\n</code></pre>\n\n<p>We can clearly see that <code>typeof obj.prop == \'undefined\'</code> and <code>obj.prop === undefined</code> are equivalent, and they do not distinguish those different situations. And <code>\'prop\' in obj</code> can detect the situation when a property hasn\'t been defined at all and doesn\'t pay attention to the property value which may be undefined.</p>\n\n<h2>So what to do?</h2>\n\n<p>1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).</p>\n\n<pre><code>obj.prop === undefined // IMHO, see "final fight" below\n</code></pre>\n\n<p>2) You want to just know if object has some property and don\'t care about its value.</p>\n\n<pre><code>\'prop\' in obj\n</code></pre>\n\n<h2>Notes:</h2>\n\n<ul>\n<li>You can\'t check an object and its property at the same time. For example, this <code>x.a === undefined</code> or this <code>typeof x.a == \'undefined\'</code> raises <code>ReferenceError: x is not defined</code> if x is not defined.</li>\n<li>Variable <code>undefined</code> is a global variable (so actually it is <code>window.undefined</code> in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is <strong>read only</strong>. So in modern browsers it can\'t be <em>redefined to true</em> as many authors love to frighten us with, but this is still a true for older browsers.</li>\n</ul>\n\n<h2>Final fight: <code>obj.prop === undefined</code> vs <code>typeof obj.prop == \'undefined\'</code></h2>\n\n<p>Pluses of <code>obj.prop === undefined</code>:</p>\n\n<ul>\n<li>It\'s a bit shorter and looks a bit prettier</li>\n<li>The JavaScript engine will give you an error if you have misspelled <code>undefined</code></li>\n</ul>\n\n<p>Minuses of <code>obj.prop === undefined</code>:</p>\n\n<ul>\n<li><code>undefined</code> can be overridden in old browsers</li>\n</ul>\n\n<p>Pluses of <code>typeof obj.prop == \'undefined\'</code>:</p>\n\n<ul>\n<li>It is really universal! It works in new and old browsers.</li>\n</ul>\n\n<p>Minuses of <code>typeof obj.prop == \'undefined\'</code>:</p>\n\n<ul>\n<li><code>\'undefned\'</code> (<em>misspelled</em>) here is just a string constant, so the JavaScript engine can\'t help you if you have misspelled it like I just did.</li>\n</ul>\n\n<h2>Update (for server-side JavaScript):</h2>\n\n<p>Node.js supports the global variable <code>undefined</code> as <code>global.undefined</code> (it can also be used without the \'global\' prefix). I don\'t know about other implementations of server-side JavaScript.</p>\n'}, {'answer_id': 18254258, 'author': 'wayneseymour', 'author_id': 352033, 'author_profile': 'https://Stackoverflow.com/users/352033', 'pm_score': 3, 'selected': False, 'text': "<p>Here is my situation:</p>\n<p>I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.</p>\n<p>There is one error I need to defend. If the arguments to the REST call were incorrect as far as the user specifying the arguments wrong, the REST call comes back basically empty.</p>\n<p>While using this post to help me defend against this, I tried this:</p>\n<pre><code>if( typeof restResult.data[0] === &quot;undefined&quot; ) { throw  &quot;Some error&quot;; }\n</code></pre>\n<p>For my situation, if restResult.data[0] === &quot;object&quot;, then I can safely start inspecting the rest of the members. If undefined then throw the error as above.</p>\n<p>What I am saying is that for my situation, all the previous suggestions in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.</p>\n"}, {'answer_id': 20679527, 'author': 'Marthijn', 'author_id': 788840, 'author_profile': 'https://Stackoverflow.com/users/788840', 'pm_score': 4, 'selected': False, 'text': '<p>In the article <em><a href="http://flippinawesome.org/2013/12/09/exploring-the-abyss-of-null-and-undefined-in-javascript/" rel="noreferrer">Exploring the Abyss of Null and Undefined in JavaScript </a></em> I read that frameworks like <a href="https://en.wikipedia.org/wiki/Underscore.js" rel="noreferrer">Underscore.js</a> use this function:</p>\n\n<pre><code>function isUndefined(obj){\n    return obj === void 0;\n}\n</code></pre>\n'}, {'answer_id': 20883574, 'author': 'bevacqua', 'author_id': 389745, 'author_profile': 'https://Stackoverflow.com/users/389745', 'pm_score': 3, 'selected': False, 'text': "<p>Compare with <code>void 0</code>, for terseness.</p>\n\n<pre><code>if (foo !== void 0)\n</code></pre>\n\n<p>It's not as verbose as <code>if (typeof foo !== 'undefined')</code></p>\n"}, {'answer_id': 21682564, 'author': 'DenisS', 'author_id': 2088061, 'author_profile': 'https://Stackoverflow.com/users/2088061', 'pm_score': 4, 'selected': False, 'text': "<h2>'<em>if (window.x) { }</em>' is error safe</h2>\n\n<p>Most likely you want <code>if (window.x)</code>. This check is safe even if x hasn't been declared (<code>var x;</code>) - browser doesn't throw an error. </p>\n\n<h2>Example: I want to know if my browser supports History API</h2>\n\n<pre><code>if (window.history) {\n    history.call_some_function();\n}\n</code></pre>\n\n<h2>How this works:</h2>\n\n<p><strong>window</strong> is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If <strong>x</strong> hasn't been declared or hasn't been set then <code>window.x</code> returns <strong>undefined</strong>. <strong>undefined</strong> leads to <strong>false</strong> when <strong>if()</strong> evaluates it.</p>\n"}, {'answer_id': 22053469, 'author': 'Ry-', 'author_id': 707111, 'author_profile': 'https://Stackoverflow.com/users/707111', 'pm_score': 8, 'selected': False, 'text': '<p>Despite being vehemently recommended by many other answers here, <code>typeof</code> <em>is a bad choice</em>. It should never be used for checking whether variables have the value <code>undefined</code>, because it acts as a combined check for the value <code>undefined</code> and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and <code>typeof</code> will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal <code>\'undefined\'</code>.</p>\n<pre><code>var snapshot = …;\n\nif (typeof snaposhot === \'undefined\') {\n    //         ^\n    // misspelled¹ – this will never run, but it won’t throw an error!\n}\n</code></pre>\n\n<pre><code>var foo = …;\n\nif (typeof foo === \'undefned\') {\n    //                   ^\n    // misspelled – this will never run, but it won’t throw an error!\n}\n</code></pre>\n<p>So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking <code>typeof module !== \'undefined\'</code> as a step in code specific to a CommonJS environment), <code>typeof</code> is a harmful choice when used on a variable, and the correct option is to compare the value directly:</p>\n<pre><code>var foo = …;\n\nif (foo === undefined) {\n    ⋮\n}\n</code></pre>\n<p>Some common misconceptions about this include:</p>\n<ul>\n<li><p>that reading an “uninitialized” variable (<code>var foo</code>) or parameter (<code>function bar(foo) { … }</code>, called as <code>bar()</code>) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become <code>undefined</code>, and are always in scope.</p>\n</li>\n<li><p>that <code>undefined</code> can be overwritten. It’s true that <code>undefined</code> isn’t a keyword, but it <em>is</em> read-only and non-configurable. There are other built-ins you probably don’t avoid despite their non-keyword status (<code>Object</code>, <code>Math</code>, <code>NaN</code>…) and practical code usually isn’t written in an actively malicious environment, so this isn’t a good reason to be worried about <code>undefined</code>. (But if you are writing a code generator, feel free to use <code>void 0</code>.)</p>\n</li>\n</ul>\n<p>With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use <code>typeof</code> for object properties. The earlier exception regarding feature detection doesn’t apply here – <code>typeof</code> only has special behaviour on variables, and expressions that reference object properties are not variables.</p>\n<p>This:</p>\n<pre><code>if (typeof foo.bar === \'undefined\') {\n    ⋮\n}\n</code></pre>\n<p>is <em>always exactly equivalent</em> to this³:</p>\n<pre><code>if (foo.bar === undefined) {\n    ⋮\n}\n</code></pre>\n<p>and taking into account the advice above, to avoid confusing readers as to why you’re using <code>typeof</code>, because it makes the most sense to use <code>===</code> to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, <strong>you should always use <code>=== undefined</code>³ here as well</strong>.</p>\n<p>Something else to consider when it comes to object properties is whether you really want to check for <code>undefined</code> at all. A given property name can be absent on an object (producing the value <code>undefined</code> when read), present on the object itself with the value <code>undefined</code>, present on the object’s prototype with the value <code>undefined</code>, or present on either of those with a non-<code>undefined</code> value. <code>\'key\' in obj</code> will tell you whether a key is anywhere on an object’s prototype chain, and <code>Object.prototype.hasOwnProperty.call(obj, \'key\')</code> will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes" rel="noreferrer">object prototypes on MDN</a> for more!</p>\n<p><sub>¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox.</sub><br />\n<sub>² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: <a href="https://bugs.chromium.org/p/project-zero/issues/detail?id=1225&amp;desc=6" rel="noreferrer">Project Zero 1225</a></sub><br />\n<sub>³ once again assuming an ES5+ environment and that <code>undefined</code> refers to the <code>undefined</code> property of the global object.</sub></p>\n'}, {'answer_id': 23463075, 'author': 'sam', 'author_id': 822138, 'author_profile': 'https://Stackoverflow.com/users/822138', 'pm_score': 4, 'selected': False, 'text': '<pre><code>"propertyName" in obj //-&gt; true | false\n</code></pre>\n'}, {'answer_id': 24243518, 'author': 'raskalbass', 'author_id': 1289868, 'author_profile': 'https://Stackoverflow.com/users/1289868', 'pm_score': 2, 'selected': False, 'text': '<p>Also, the same things can be written shorter:</p>\n<pre><code>if (!variable){\n    // Do it if the variable is undefined\n}\n</code></pre>\n<p>or</p>\n<pre><code>if (variable){\n    // Do it if the variable is defined\n}\n</code></pre>\n'}, {'answer_id': 24277572, 'author': 'Juan Garcia', 'author_id': 1802325, 'author_profile': 'https://Stackoverflow.com/users/1802325', 'pm_score': 3, 'selected': False, 'text': "<p>All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined':</p>\n<pre><code>var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){\n  return ((prop in obj) &amp;&amp; (typeof obj[prop] == 'undefined'));\n};\n</code></pre>\n<p>Example:</p>\n<pre><code>var a = { b : 1, e : null };\na.c = a.d;\n\nhasUndefinedProperty(a, 'b'); // false: b is defined as 1\nhasUndefinedProperty(a, 'c'); // true: c is defined as undefined\nhasUndefinedProperty(a, 'd'); // false: d is undefined\nhasUndefinedProperty(a, 'e'); // false: e is defined as null\n\n// And now...\ndelete a.c ;\nhasUndefinedProperty(a, 'c'); // false: c is undefined\n</code></pre>\n<p>Too bad that this been the right answer and is buried in wrong answers &gt;_&lt;</p>\n<p>So, for anyone who pass by, I will give you undefined's for free!!</p>\n<pre><code>var undefined ; undefined ; // undefined\n({}).a ;                    // undefined\n[].a ;                      // undefined\n''.a ;                      // undefined\n(function(){}()) ;          // undefined\nvoid(0) ;                   // undefined\neval() ;                    // undefined\n1..a ;                      // undefined\n/a/.a ;                     // undefined\n(true).a ;                  // undefined\n</code></pre>\n"}, {'answer_id': 24626893, 'author': 'Angelin Nadar', 'author_id': 412591, 'author_profile': 'https://Stackoverflow.com/users/412591', 'pm_score': 3, 'selected': False, 'text': '<p>Going through the comments, for those who want to check both is it undefined or its value is null:</p>\n\n<pre><code>//Just in JavaScript\nvar s; // Undefined\nif (typeof s == "undefined" || s === null){\n    alert(\'either it is undefined or value is null\')\n}\n</code></pre>\n\n<p>If you are using jQuery Library then <code>jQuery.isEmptyObject()</code> will suffice for both cases,</p>\n\n<pre><code>var s; // Undefined\njQuery.isEmptyObject(s); // Will return true;\n\ns = null; // Defined as null\njQuery.isEmptyObject(s); // Will return true;\n\n//Usage\nif (jQuery.isEmptyObject(s)) {\n    alert(\'Either variable:s is undefined or its value is null\');\n} else {\n     alert(\'variable:s has value \' + s);\n}\n\ns = \'something\'; // Defined with some value\njQuery.isEmptyObject(s); // Will return false;\n</code></pre>\n'}, {'answer_id': 26273383, 'author': 'Seti', 'author_id': 3535045, 'author_profile': 'https://Stackoverflow.com/users/3535045', 'pm_score': 2, 'selected': False, 'text': '<p>I would like to show you something I\'m using in order to protect the <code>undefined</code> variable:</p>\n\n<pre><code>Object.defineProperty(window, \'undefined\', {});\n</code></pre>\n\n<p>This forbids anyone to change the <code>window.undefined</code> value therefore destroying the code based on that variable. If using <code>"use strict"</code>, anything trying to change its value will end in error, otherwise it would be silently ignored.</p>\n'}, {'answer_id': 27474938, 'author': 'Vitalii Fedorenko', 'author_id': 288671, 'author_profile': 'https://Stackoverflow.com/users/288671', 'pm_score': 3, 'selected': False, 'text': '<p>If you are using Angular: </p>\n\n<pre><code>angular.isUndefined(obj)\nangular.isUndefined(obj.prop)\n</code></pre>\n\n<p>Underscore.js:</p>\n\n<pre><code>_.isUndefined(obj) \n_.isUndefined(obj.prop) \n</code></pre>\n'}, {'answer_id': 28522648, 'author': 'Travis', 'author_id': 4303905, 'author_profile': 'https://Stackoverflow.com/users/4303905', 'pm_score': 4, 'selected': False, 'text': '<p>Reading through this, I\'m amazed I didn\'t see this. I have found multiple algorithms that would work for this.</p>\n\n<h1>Never Defined</h1>\n\n<p>If the value of an object was never defined, this will prevent from returning <code>true</code> if it is defined as <code>null</code> or <code>undefined</code>. This is helpful if you want true to be returned for values set as <code>undefined</code></p>\n\n<pre><code>if(obj.prop === void 0) console.log("The value has never been defined");\n</code></pre>\n\n<h1>Defined as undefined Or never Defined</h1>\n\n<p>If you want it to result as <code>true</code> for values defined with the value of <code>undefined</code>, or never defined, you can simply use <code>=== undefined</code></p>\n\n<pre><code>if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");\n</code></pre>\n\n<h1>Defined as a falsy value, undefined,null, or never defined.</h1>\n\n<p>Commonly, people have asked me for an algorithm to figure out if a value is either falsy, <code>undefined</code>, or <code>null</code>. The following works.</p>\n\n<pre><code>if(obj.prop == false || obj.prop === null || obj.prop === undefined) {\n    console.log("The value is falsy, null, or undefined");\n}\n</code></pre>\n'}, {'answer_id': 28902597, 'author': 'Val', 'author_id': 1083704, 'author_profile': 'https://Stackoverflow.com/users/1083704', 'pm_score': 3, 'selected': False, 'text': '<p>I use <code>if (this.variable)</code> to test if it is defined. A simple <code>if (variable)</code>, <a href="https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property/12589152#12589152">recommended in a previous answer</a>, fails for me.</p>\n<p>It turns out that it works only when a variable is a field of some object, <code>obj.someField</code> to check if it is defined in the dictionary. But we can use <code>this</code> or <code>window</code> as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>if (this.abc) \n    alert("defined"); \nelse \n    alert("undefined");\n\nabc = "abc";\nif (this.abc) \n    alert("defined"); \nelse \n    alert("undefined");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It first detects that variable <code>abc</code> is undefined and it is defined after initialization.</p>\n'}, {'answer_id': 32009076, 'author': 'Mike Clark', 'author_id': 4261022, 'author_profile': 'https://Stackoverflow.com/users/4261022', 'pm_score': 2, 'selected': False, 'text': '<p>Use:</p>\n\n<p><strong>To check if property is undefined:</strong></p>\n\n<pre><code>if (typeof something === "undefined") {\n    alert("undefined");\n}\n</code></pre>\n\n<p><strong>To check if property is not undefined:</strong></p>\n\n<pre><code>if (typeof something !== "undefined") {\n    alert("not undefined");\n}\n</code></pre>\n'}, {'answer_id': 34782448, 'author': 'lzl124631x', 'author_id': 3127828, 'author_profile': 'https://Stackoverflow.com/users/3127828', 'pm_score': 2, 'selected': False, 'text': '<p>From lodash.js.</p>\n<pre><code>var undefined;\nfunction isUndefined(value) {\n  return value === undefined;\n}\n</code></pre>\n<p>It creates a <em>local</em> variable named <code>undefined</code> which is initialized with the default value -- the real <code>undefined</code>, then compares <code>value</code> with the variable <code>undefined</code>.</p>\n<hr />\n<p>Update 9/9/2019</p>\n<p>I found Lodash updated its implementation. See <a href="https://github.com/lodash/lodash/issues/4041" rel="nofollow noreferrer">my issue</a> and <a href="https://github.com/lodash/lodash/blob/4ea8c2ec249be046a0f4ae32539d652194caf74f/isUndefined.js#L17" rel="nofollow noreferrer">the code</a>.</p>\n<p>To be bullet-proof, simply use:</p>\n<pre><code>function isUndefined(value) {\n  return value === void 0;\n}\n</code></pre>\n'}, {'answer_id': 35768990, 'author': 'Marian Klühspies', 'author_id': 2324388, 'author_profile': 'https://Stackoverflow.com/users/2324388', 'pm_score': 3, 'selected': False, 'text': '<p>There is a nice and elegant way to assign a defined property to a new variable if it is defined or assign a default value to it as a fallback if it’s undefined.</p>\n<pre><code>var a = obj.prop || defaultValue;\n</code></pre>\n<p>It’s suitable if you have a function, which receives an additional configuration property:</p>\n<pre><code>var yourFunction = function(config){\n\n   this.config = config || {};\n   this.yourConfigValue = config.yourConfigValue || 1;\n   console.log(this.yourConfigValue);\n}\n</code></pre>\n<p>Now executing</p>\n<pre><code>yourFunction({yourConfigValue:2});\n//=&gt; 2\n\nyourFunction();\n//=&gt; 1\n\nyourFunction({otherProperty:5});\n//=&gt; 1\n</code></pre>\n'}, {'answer_id': 43058440, 'author': 'Patrick Roberts', 'author_id': 1541563, 'author_profile': 'https://Stackoverflow.com/users/1541563', 'pm_score': 1, 'selected': False, 'text': '<p>I\'m surprised I haven\'t seen this suggestion yet, but it gets even more specificity than testing with <code>typeof</code>. Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor" rel="nofollow noreferrer"><code>Object.getOwnPropertyDescriptor()</code></a> if you need to know whether an object property was initialized with <code>undefined</code> or if it was never initialized:</p>\n<pre><code>// to test someObject.someProperty\nvar descriptor = Object.getOwnPropertyDescriptor(someObject, \'someProperty\');\n\nif (typeof descriptor === \'undefined\') {\n  // was never initialized\n} else if (typeof descriptor.value === \'undefined\') {\n  if (descriptor.get || descriptor.set) {\n    // is an accessor property, defined via getter and setter\n  } else {\n    // is initialized with `undefined`\n  }\n} else {\n  // is initialized with some other value\n}\n</code></pre>\n'}, {'answer_id': 43527813, 'author': 'Bekim Bacaj', 'author_id': 5896426, 'author_profile': 'https://Stackoverflow.com/users/5896426', 'pm_score': 0, 'selected': False, 'text': "<p>This is probably the only explicit form of determining if the existing property-name has an explicit and intended value of <code>undefined</code>; which is, nonetheless, a JavaScript type.</p>\n<pre><code>&quot;propertyName&quot; in containerObject &amp;&amp; &quot;&quot;+containerObject[&quot;propertyName&quot;] == &quot;undefined&quot;;\n&gt;&gt; true \\ false\n</code></pre>\n<p>This expression will only return <code>true</code> if the property name of the given context exists (truly) and only if its intended value is explicitly <code>undefined</code>.</p>\n<p>There will be no false positives like with empty or blank strings zeros nulls or empty arrays and alike. This does exactly that. Checks i.e., makes sure the property name exists (otherwise it would be a false positive), than it explicitly checks if its value is <code>undefined</code> e.g. of an undefined JavaScript type in it's string representation form (literally &quot;undefined&quot;) therefore <code>==</code> instead of <code>===</code> because no further conversion is possible. And this expression will only return true if both, that is all conditions are met. E.g. if the property-name doesn't exist, - it will return false. Which is the only correct return since nonexistent properties can't have values, not even an undefined one.</p>\n<p>Example:</p>\n<pre><code>containerObject = { propertyName: void &quot;anything&quot; }\n&gt;&gt; Object { propertyName: undefined }\n\n// Now the testing\n\n&quot;propertyName&quot; in containerObject &amp;&amp; &quot;&quot;+containerObject[&quot;propertyName&quot;] == &quot;undefined&quot;;\n&gt;&gt; true\n\n/* Which makes sure that nonexistent property will not return a false positive\n * unless it is previously defined  */\n\n&quot;foo&quot; in containerObject &amp;&amp; &quot;&quot;+containerObject[&quot;foo&quot;] == &quot;undefined&quot;;\n&gt;&gt; false\n</code></pre>\n"}, {'answer_id': 44161028, 'author': 'Alireza', 'author_id': 5423108, 'author_profile': 'https://Stackoverflow.com/users/5423108', 'pm_score': 4, 'selected': False, 'text': '<p>Simply anything is not defined in JavaScript, is <strong>undefined</strong>, doesn\'t matter if it\'s a property inside an <strong>Object/Array</strong> or as just a simple variable...</p>\n\n<p>JavaScript has <code>typeof</code> which make it very easy to detect an undefined variable.</p>\n\n<p>Simply check if <code>typeof whatever === \'undefined\'</code> and it will return a boolean.</p>\n\n<p>That\'s how the famous function <code>isUndefined()</code> in AngularJs v.1x is written:</p>\n\n<pre><code>function isUndefined(value) {return typeof value === \'undefined\';} \n</code></pre>\n\n<p>So as you see the function receive a value, if that value is defined, it will return <code>false</code>, otherwise for undefined values, return <code>true</code>. </p>\n\n<p>So let\'s have a look what gonna be the results when we passing values, including object properties like below, this is the list of variables we have:</p>\n\n<pre><code>var stackoverflow = {};\nstackoverflow.javascipt = \'javascript\';\nvar today;\nvar self = this;\nvar num = 8;\nvar list = [1, 2, 3, 4, 5];\nvar y = null;\n</code></pre>\n\n<p>and we check them as below, you can see the results in front of them as a comment:</p>\n\n<pre><code>isUndefined(stackoverflow); //false\nisUndefined(stackoverflow.javascipt); //false\nisUndefined(today); //true\nisUndefined(self); //false\nisUndefined(num); //false\nisUndefined(list); //false\nisUndefined(y); //false\nisUndefined(stackoverflow.java); //true\nisUndefined(stackoverflow.php); //true\nisUndefined(stackoverflow &amp;&amp; stackoverflow.css); //true\n</code></pre>\n\n<p>As you see we can check anything with using something like this in our code, as mentioned you can simply use <code>typeof</code> in your code, but if you are using it over and over, create a function like the angular sample which I share and keep reusing as following DRY code pattern.</p>\n\n<p>Also one more thing, for checking property on an object in a real application which you not sure even the object exists or not, check if the object exists first.</p>\n\n<p>If you check a property on an object and the object doesn\'t exist, will throw an error and stop the whole application running.</p>\n\n<pre><code>isUndefined(x.css);\nVM808:2 Uncaught ReferenceError: x is not defined(…)\n</code></pre>\n\n<p>So simple you can wrap inside an if statement like below:</p>\n\n<pre><code>if(typeof x !== \'undefined\') {\n  //do something\n}\n</code></pre>\n\n<p>Which also equal to isDefined in Angular 1.x...</p>\n\n<pre><code>function isDefined(value) {return typeof value !== \'undefined\';}\n</code></pre>\n\n<p>Also other javascript frameworks like underscore has similar defining check, but I recommend you use <code>typeof</code> if you already not using any frameworks.</p>\n\n<p>I also add this section from MDN which has got useful information about typeof, undefined and void(0).</p>\n\n<blockquote>\n  <p><strong>Strict equality and undefined</strong> <br> You can use undefined and the strict equality and inequality operators to determine whether a variable has\n  a value. In the following code, the variable x is not defined, and the\n  if statement evaluates to true.</p>\n</blockquote>\n\n<pre><code>var x;\nif (x === undefined) {\n   // these statements execute\n}\nelse {\n   // these statements do not execute\n}\n</code></pre>\n\n<blockquote>\n  <p>Note: The strict equality operator rather than the standard equality\n  operator must be used here, because x == undefined also checks whether\n  x is null, while strict equality doesn\'t. null is not equivalent to\n  undefined. See comparison operators for details.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n  <p><strong>Typeof operator and undefined</strong> <br>\n  Alternatively, typeof can be used:</p>\n</blockquote>\n\n<pre><code>var x;\nif (typeof x === \'undefined\') {\n   // these statements execute\n}\n</code></pre>\n\n<blockquote>\n  <p>One reason to use typeof is that it does not throw an error if the\n  variable has not been declared.</p>\n</blockquote>\n\n<pre><code>// x has not been declared before\nif (typeof x === \'undefined\') { // evaluates to true without errors\n   // these statements execute\n}\n\nif (x === undefined) { // throws a ReferenceError\n\n}\n</code></pre>\n\n<blockquote>\n  <p>However, this kind of technique should be avoided. JavaScript is a\n  statically scoped language, so knowing if a variable is declared can\n  be read by seeing whether it is declared in an enclosing context. The\n  only exception is the global scope, but the global scope is bound to\n  the global object, so checking the existence of a variable in the\n  global context can be done by checking the existence of a property on\n  the global object (using the in operator, for instance).</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n  <p><strong>Void operator and undefined</strong></p>\n  \n  <p>The void operator is a third alternative.</p>\n</blockquote>\n\n<pre><code>var x;\nif (x === void 0) {\n   // these statements execute\n}\n\n// y has not been declared before\nif (y === void 0) {\n   // throws a ReferenceError (in contrast to `typeof`)\n}\n</code></pre>\n\n<p>more > <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 44556602, 'author': 'IliasT', 'author_id': 3015469, 'author_profile': 'https://Stackoverflow.com/users/3015469', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m assuming you\'re going to also want to check for it being <em>either</em> <code>undefined</code> or <code>null</code>. If so, I suggest:</p>\n<p><code>myVar == null</code></p>\n<p>This is one of the only times a <strong>double equals</strong> is very helpful as it will evaluate to <code>true</code> when <code>myVar</code> is <code>undefined</code> or <code>null</code>, but it will evaluate to <code>false</code> when it is other falsey values such as <code>0</code>, <code>false</code>, <code>\'\'</code>, and <code>NaN</code>.</p>\n<p>This the actual <a href="https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L11987" rel="nofollow noreferrer">the source code</a> for Lodash\'s <a href="https://lodash.com/docs/4.17.4#isNil" rel="nofollow noreferrer"><code>isNil</code></a> method.</p>\n'}, {'answer_id': 46988171, 'author': 'blackmiaool', 'author_id': 4831179, 'author_profile': 'https://Stackoverflow.com/users/4831179', 'pm_score': 3, 'selected': False, 'text': '<p>I provide three ways here for those who expect weird answers:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function isUndefined1(val) {\n    try {\n        val.a;\n    } catch (e) {\n        return /undefined/.test(e.message);\n    }\n    return false;\n}\n\nfunction isUndefined2(val) {\n    return !val &amp;&amp; val+\'\' === \'undefined\';\n}\n\nfunction isUndefined3(val) {\n    const defaultVal = {};\n    return ((input = defaultVal) =&gt; input === defaultVal)(val);\n}\n\nfunction test(func){\n    console.group(`test start :`+func.name);\n    console.log(func(undefined));\n    console.log(func(null));\n    console.log(func(1));\n    console.log(func("1"));\n    console.log(func(0));\n    console.log(func({}));\n    console.log(func(function () { }));\n    console.groupEnd();\n}\ntest(isUndefined1);\ntest(isUndefined2);\ntest(isUndefined3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>isUndefined1:</h3>\n<p>Try to get a property of the input value, and check the error message if it exists. If the input value is undefined, the error message would be <em>Uncaught TypeError: Cannot read property \'b\' of undefined</em>.</p>\n<h3>isUndefined2:</h3>\n<p>Convert the input value to a string to compare with <code>&quot;undefined&quot;</code> and ensure it\'s a negative value.</p>\n<h3>isUndefined3:</h3>\n<p>In JavaScript, an optional parameter works when the input value is exactly <code>undefined</code>.</p>\n'}, {'answer_id': 49158713, 'author': 'Aditya Vashishtha', 'author_id': 8618959, 'author_profile': 'https://Stackoverflow.com/users/8618959', 'pm_score': 0, 'selected': False, 'text': "<p>You can use the JavaScript object function like this:</p>\n<pre><code>var ojb ={\n    age: 12\n}\n\nif(ojb.hasOwnProperty('name')){\n    console.log('property exists and is not undefined');\n}\n</code></pre>\n<p>The above method returns <code>true</code> if it got that property or the property is not undefined.</p>\n"}, {'answer_id': 49412206, 'author': 'Sarkis Arutiunian', 'author_id': 5278472, 'author_profile': 'https://Stackoverflow.com/users/5278472', 'pm_score': 2, 'selected': False, 'text': "<p>You can also use a Proxy. It will work with nested calls, but it will require one extra check:</p>\n<pre><code>function resolveUnknownProps(obj, resolveKey) {\n  const handler = {\n    get(target, key) {\n      if (\n        target[key] !== null &amp;&amp;\n        typeof target[key] === 'object'\n      ) {\n        return resolveUnknownProps(target[key], resolveKey);\n      } else if (!target[key]) {\n        return resolveUnknownProps({ [resolveKey]: true }, resolveKey);\n      }\n\n      return target[key];\n    },\n  };\n\n  return new Proxy(obj, handler);\n}\n\nconst user = {}\n\nconsole.log(resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else); // { isUndefined: true }\n</code></pre>\n<p>So you will use it like:</p>\n<pre><code>const { isUndefined } = resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else;\nif (!isUndefined) {\n  // Do something\n}\n</code></pre>\n"}, {'answer_id': 49706807, 'author': 'Aliaksandr Sushkevich', 'author_id': 7600492, 'author_profile': 'https://Stackoverflow.com/users/7600492', 'pm_score': 0, 'selected': False, 'text': '<p>There are a few little helpers in the <a href="https://lodash.com/" rel="nofollow noreferrer">Lodash</a> library:</p>\n<p><a href="https://lodash.com/docs/4.17.5#isUndefined" rel="nofollow noreferrer">isUndefined</a> - to check if <em>value</em> is <code>undefined</code>.</p>\n<pre><code>_.isUndefined(undefined) // =&gt; true\n_.isUndefined(null) // =&gt; false\n</code></pre>\n<p><a href="https://lodash.com/docs/4.17.5#has" rel="nofollow noreferrer">has</a> - to check if object contains a property</p>\n<pre><code>const object = { \'a\': { \'b\': 2 } }\n\n_.has(object, \'a.b\') // =&gt; true\n_.has(object, \'a.c\') // =&gt; false\n</code></pre>\n'}, {'answer_id': 51478480, 'author': 'Krishnadas PC', 'author_id': 2295484, 'author_profile': 'https://Stackoverflow.com/users/2295484', 'pm_score': 1, 'selected': False, 'text': "<p>Introduced in <strong>ECMAScript 6</strong>, we can now deal with <code>undefined</code> in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.</p>\n<pre><code>var handler = {\n  get: function(target, name) {\n    return name in target ? target[name] : 'N/A';\n  }\n};\n\nvar p = new Proxy({}, handler);\np.name = 'Kevin';\nconsole.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)\n</code></pre>\n<p>Will output the below text without getting any undefined.</p>\n<pre><code>Name: Kevin , Age: N/A , Gender: N/A\n</code></pre>\n"}, {'answer_id': 52275862, 'author': 'CodeDraken', 'author_id': 10326132, 'author_profile': 'https://Stackoverflow.com/users/10326132', 'pm_score': 2, 'selected': False, 'text': "<p>A simple way to check if a key exists is to use <code>in</code>:</p>\n<pre><code>if (key in obj) {\n  // Do something\n} else {\n  // Create key\n}\n\nconst obj = {\n  0: 'abc',\n  1: 'def'\n}\n\nconst hasZero = 0 in obj\n\nconsole.log(hasZero) // true\n</code></pre>\n"}, {'answer_id': 58129331, 'author': 'Przemek Struciński', 'author_id': 8680601, 'author_profile': 'https://Stackoverflow.com/users/8680601', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019" rel="noreferrer">ECMAScript\xa010</a> introduced a new feature - <strong>optional chaining</strong> which you can use to use a property of an object only when an object is defined like this:</p>\n<pre><code>const userPhone = user?.contactDetails?.phone;\n</code></pre>\n<p>It will reference to the phone property only when user and contactDetails are defined.</p>\n<p>Ref. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n'}, {'answer_id': 59999090, 'author': 'Ravi Makwana', 'author_id': 6631280, 'author_profile': 'https://Stackoverflow.com/users/6631280', 'pm_score': 0, 'selected': False, 'text': '<p>I found this article, <em><a href="https://dmitripavlutin.com/7-tips-to-handle-undefined-in-javascript/" rel="nofollow noreferrer">7 Tips to Handle undefined in JavaScript</a></em>, which is showing really interesting things about <code>undefined</code>\nlike:</p>\n<p>The existence of undefined is a consequence of JavaScript’s permissive nature that allows the usage of:</p>\n<ul>\n<li>uninitialized variables</li>\n<li>non-existing object properties or methods</li>\n<li>out of bounds indexes to access array elements</li>\n<li>the invocation result of a function that returns nothing</li>\n</ul>\n'}, {'answer_id': 61550879, 'author': 'Kiran Maniya', 'author_id': 8203357, 'author_profile': 'https://Stackoverflow.com/users/8203357', 'pm_score': 0, 'selected': False, 'text': '<p>In JavaScript, there are <strong>truthy</strong> and <strong>falsy</strong> expressions. If you want to check if the property is undefined or not, there is a straight way of using an <strong>if</strong> condition as given,</p>\n<ol>\n<li>Using <b>truthy/falsy</b> concept.</li>\n</ol>\n<pre class="lang-js prettyprint-override"><code>if(!ob.someProp){\n    console.log(\'someProp is falsy\')\n}\n</code></pre>\n<p>However, there are several more approaches to check the object has property or not, but it seems long to me. Here are those.</p>\n<ol start="2">\n<li>Using <b><code>=== undefined</code></b> check in <b><code>if</code></b> condition</li>\n</ol>\n<pre class="lang-js prettyprint-override"><code>if(ob.someProp === undefined){\n    console.log(\'someProp is undefined\')\n}\n</code></pre>\n<ol start="3">\n<li>Using <b><code>typeof</code></b></li>\n</ol>\n<p><b><code>typeof</code></b> acts as a combined check for the value undefined and for whether a variable exists.</p>\n<pre class="lang-js prettyprint-override"><code>if(typeof ob.someProp === \'undefined\'){\n    console.log(\'someProp is undefined\')\n}\n</code></pre>\n<ol start="4">\n<li>Using <b><code>hasOwnProperty</code></b> method</li>\n</ol>\n<p>The JavaScript object has built in the <code>hasOwnProperty</code> function in the object prototype.</p>\n<pre class="lang-js prettyprint-override"><code>if(!ob.hasOwnProperty(\'someProp\')){\n    console.log(\'someProp is undefined\')\n}\n</code></pre>\n<p>Not going in deep, but the 1<sup>st</sup> way looks shortened and good to me. Here are the details on <a href="https://howtodoinjava.com/typescript/truthy-and-falsy/" rel="nofollow noreferrer">truthy/falsy</a> values in JavaScript and <code>undefined</code> is the falsy value listed in there. So the <code>if</code> condition behaves normally without any glitch. Apart from the <code>undefined</code>, values <code>NaN</code>, <code>false</code> (Obviously), <code>\'\'</code> (empty string) and number <code>0</code> are also the falsy values.</p>\n<blockquote>\n<p><strong>Warning</strong>: <em>Make sure the property value does not contain any falsy value, otherwise the <code>if</code> condition will return false. For such a case, you can use the <code>hasOwnProperty</code> method</em></p>\n</blockquote>\n'}, {'answer_id': 61607190, 'author': 'Sajad Saderi', 'author_id': 9845404, 'author_profile': 'https://Stackoverflow.com/users/9845404', 'pm_score': 3, 'selected': False, 'text': '<p>There is a very easy and simple way.</p>\n<p>You can use <strong>optional chaining</strong>:</p>\n<pre><code>x = {prop:{name:&quot;sajad&quot;}}\n\nconsole.log(x.prop?.name) // Output is: &quot;sajad&quot;\nconsole.log(x.prop?.lastName) // Output is: undefined\n</code></pre>\n<p>or</p>\n<pre><code>if(x.prop?.lastName) // The result of this \'if\' statement is false and is not throwing an error\n</code></pre>\n<p>You can use optional chaining even for functions or arrays.</p>\n<p>As of mid-2020 this is not universally implemented. Check the documentation at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n'}, {'answer_id': 63021093, 'author': 'Kamil Kiełczewski', 'author_id': 860099, 'author_profile': 'https://Stackoverflow.com/users/860099', 'pm_score': 0, 'selected': False, 'text': '<h1>Review</h1>\n<p>A lot of the given answers give a wrong result because they do not distinguish between the case when an object property does not exist and the case when a property has value <code>undefined</code>. Here is <strong>proof</strong> for most popular solutions:</p>\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {\n  a: 666,\n  u: undefined // The \'u\' property has value \'undefined\'\n               // The \'x\' property does not exist\n}\n\nconsole.log(\'&gt;&gt;&gt; good results:\');\nconsole.log(\'A\', "u" in obj, "x" in obj);\nconsole.log(\'B\', obj.hasOwnProperty("u"),      obj.hasOwnProperty("x"));\n\nconsole.log(\'\\n&gt;&gt;&gt; bad results:\');\nconsole.log(\'C\', obj.u === undefined,          obj.x === undefined);\nconsole.log(\'D\', obj.u == undefined,           obj.x == undefined);\nconsole.log(\'E\', obj["u"] === undefined,       obj["x"] === undefined);\nconsole.log(\'F\', obj["u"] == undefined,        obj["x"] == undefined);\nconsole.log(\'G\', !obj.u,                      !obj.x);\nconsole.log(\'H\', typeof obj.u === \'undefined\', typeof obj.x === \'undefined\');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 64125263, 'author': 'Hanzla Habib', 'author_id': 3946527, 'author_profile': 'https://Stackoverflow.com/users/3946527', 'pm_score': 2, 'selected': False, 'text': '<p>In recent JavaScript release there is new chaining operator introduced, which is most probably best way to check if property exists else it will give you undefined</p>\n<p>see example below</p>\n<pre><code>  const adventurer = {\n  name: \'Alice\',\n  cat: {\n    name: \'Dinah\'\n  }\n};\n\nconst dogName = adventurer.dog?.name;\nconsole.log(dogName);\n// expected output: undefined\n\nconsole.log(adventurer.someNonExistentMethod?.());\n// expected output: undefined\n</code></pre>\n<p>We can replace this old syntax</p>\n<pre><code>if (response &amp;&amp; response.data &amp;&amp; response.data.someData &amp;&amp; response.data.someData.someMoreData) {}\n</code></pre>\n<p>with this neater syntax</p>\n<pre><code>if( response?.data?.someData?.someMoreData) {}\n</code></pre>\n<p>This syntax is not supported in IE, Opera, safari &amp; samsund android</p>\n<p>for more detail you can check this URL</p>\n<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining</a></p>\n'}, {'answer_id': 65342690, 'author': 'Adam111p', 'author_id': 3058581, 'author_profile': 'https://Stackoverflow.com/users/3058581', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Version for the use of dynamic variables</strong>\nDid you know?</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var boo =\'lala\';\n\nfunction check(){\n  if(this[\'foo\']){\n        console.log(\'foo is here\');}\n  else{\n        console.log(\'have no foo\');\n      }\n\n  if(this[\'boo\']){\n        console.log(\'boo is here\');}\n  else{\n        console.log(\'have no boo\');\n      }\n}\n\ncheck();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 68147770, 'author': 'Balaji', 'author_id': 8389576, 'author_profile': 'https://Stackoverflow.com/users/8389576', 'pm_score': 0, 'selected': False, 'text': '<p>handle undefined</p>\n<pre><code>function isUndefined(variable,defaultvalue=\'\'){\n\n    if (variable == undefined ) return defaultvalue;\n    \n    return variable;\n\n}\n</code></pre>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj={\nund:undefined,\nnotundefined:\'hi i am not undefined\'\n}\n\n\nfunction isUndefined(variable,defaultvalue=\'\'){\n\n    if (variable == undefined )\n    { \n        return defaultvalue;\n    }\n    return variable\n\n}\n\nconsole.log(isUndefined(obj.und,\'i am print\'))\nconsole.log(isUndefined(obj.notundefined,\'i am print\'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 69569312, 'author': 'Ali Yaghoubi', 'author_id': 11662335, 'author_profile': 'https://Stackoverflow.com/users/11662335', 'pm_score': 2, 'selected': False, 'text': '<p>We at <strong>ES6</strong> can with <code>!!</code> Convert all <strong>values to Boolean</strong>.\nUsing this, all <em>falsy</em> values become <em>false</em>.</p>\n<p><strong>First solution</strong></p>\n<pre><code>if (!(!!variable)) {\n    // Code\n}\n</code></pre>\n<p><strong>Second solution</strong></p>\n<pre><code>if (!variable) {\n    // Code\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/27509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']