Skip to content
Fix Code Error

Detecting an undefined object property

March 13, 2021 by Code Error
Posted By: Matt Sheppard

What’s the best way of checking if an object property in JavaScript is undefined?

Solution

The usual way to check if the value of a property is the special value undefined, is:

if(o.myProperty === undefined) {
  alert("myProperty value is the special value `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try and access it:

if(!o.hasOwnProperty('myProperty')) {
  alert("myProperty does not exist");
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined) identifier without an early error:

if(typeof myVariable === 'undefined') {
  alert('myVariable is either the special value `undefined`, or it has not been declared');
}

In versions of JavaScript prior to ECMAScript 5, the property named “undefined” on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

However, in modern JavaScript, “undefined” is not a keyword, and so variables inside functions can be named “undefined” and shadow the global property.

If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

if(myVariable === void 0) {
  alert("myVariable is the special value `undefined`");
}
Answered By: Erwin

Related Articles

  • What is the scope of variables in JavaScript?
  • Notify ObservableCollection when Item changes
  • Polymer data bind without dom-bind
  • What does this symbol mean in JavaScript?
  • What are the default access modifiers in C#?
  • R: Conditional summing in R
  • Limitations on polymer conditional templates?
  • How can I access and process nested objects, arrays or JSON?
  • How do I check if an object has a specific property…
  • Smart way to truncate long strings
  • Conditional sum data in R
  • setTimeout function not working : javascript
  • Ember's registerBoundHelper and handlebar blocks
  • How to create an alert the fade after a duration in Vuetify?
  • configure: error: C compiler cannot create executables
  • JavaScript isset() equivalent
  • What does "Fatal error: Unexpectedly found nil while…
  • How to determine the current iPhone/device model?
  • JSON.Parse,'Uncaught SyntaxError: Unexpected token o
  • Form field border-radius is not working only on the…
  • Text File Parsing and convert to JSON?
  • Getting Bad Request 400 when sending data to django…
  • C# parse FHIR bundle - read resources
  • Flex: REJECT rejects one character at a time?
  • unable to remove file that really exists - fatal:…
  • How do I correctly clone a JavaScript object?
  • Using Auto Layout in UITableView for dynamic cell…
  • hasOwnProperty in JavaScript
  • How to deserialize Arraylist items into concrete…
  • Identifying and solving…
  • C++ template,typename and operator
  • XMLHttpRequest cannot load ✘✘✘ No…
  • How to compare arrays in JavaScript?
  • Polymer 1.0 observe not firing for a filter
  • C++ OpenGL stb_image.h errors
  • Fastest way to iterate over all the chars in a String
  • The definitive guide to form-based website authentication
  • Each for object?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • No 'Access-Control-Allow-Origin' header is present…
  • How to detect if multiple keys are pressed at once…
  • Object comparison in JavaScript
  • How to querySelect Lit-Element that is within…
  • Is object empty?
  • For-each over an array in JavaScript
  • Android APK signatures V1 and V2 conflict
  • How do JavaScript closures work?
  • What is the best practices with declaring custom…
  • What is an optional value in Swift?
  • What is a NullReferenceException, and how do I fix it?
  • How to use setTimeout on vuex action?
  • What does a "Cannot find symbol" or "Cannot resolve…
  • What is property in hasOwnProperty in JavaScript?
  • How do I pass data in $router.push in Vue.js?
  • Getter and Setter declaration in .NET
  • What is the purpose of willSet and didSet in Swift?
  • Start redis-server with config file
  • Best way to replace multiple characters in a string?
  • Peak signal detection in realtime timeseries data
  • Reference - What does this regex mean?
  • SwiftUI Button if Statement
  • backbone.js set model internal attributes hash directly
  • commandButton/commandLink/ajax action/listener…
  • How to use html template with vue.js
  • What are the rules about using an underscore in a…
  • Onclick, the button moves down, why can that due to?
  • How to iterate over a JavaScript object?
  • Use of Jquery on scroll event
  • Usage of __slots__?
  • Change one value based on another value in pandas
  • How can I fix MySQL error #1064?
  • Difference between `constexpr` and `const`
  • Polymer 1.0 boolean property having default value…
  • Vue.js - emit to update array not working
  • data.table vs dplyr: can one do something well the…
  • How to check if a variable is both null and /or…
  • bounded arrays vs unbounded arrays in C++
  • Filtering an object based on key, then constructing…
  • object.hasOwnProperty is not a function when spying…
  • What are the undocumented features and limitations…
  • Is there a way to have a switch statement for an…
  • Difference between variable declaration syntaxes in…
  • What are type hints in Python 3.5?
  • How do I extract data from JSON with PHP?
  • Detecting which UIButton was pressed in a UITableView
  • How do I include a JavaScript file in another…
  • Ember computed property not being updated
  • Best practice multi language website
  • What are access specifiers? Should I inherit with…
  • Why does C++ code for testing the Collatz conjecture…
  • How does JavaScript .prototype work?
  • Am I paranoid? "Brutally" big Polymer website after…
  • How does PHP 'foreach' actually work?
  • How do I add a simple onClick event handler to a…
  • "No such file or directory" error when executing a binary
  • Accessing an array out of bounds gives no error, why?
  • call a component from another component in vue.js
  • JavaScript: filter() for Objects
  • How do I enumerate the properties of a JavaScript object?
  • Get the name of an object's type

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I remove duplicate rows?

Next Post:

Better way to set distance between flexbox items

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error