Skip to content
Fix Code Error

How can I check for “undefined” in JavaScript?

March 13, 2021 by Code Error
Posted By: Anonymous

What is the most appropriate way to test if a variable is undefined in JavaScript?

I’ve seen several possible ways:

if (window.myVariable)

Or

if (typeof(myVariable) != "undefined")

Or

if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?

Solution

If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn’t been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:

if (typeof myVar !== 'undefined')

Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "foo";
"foo" == undefined // true

As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

if (window.myVar) will also include these falsy values, so it’s not very robust:

false
0
""
NaN
null
undefined

Thanks to @CMS for pointing out that your third case – if (myVariable) can also throw an error in two cases. The first is when the variable hasn’t been defined which throws a ReferenceError.

// abc was never declared.
if (abc) {
    // ReferenceError: abc is not defined
} 

The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if (myVariable) {
    // Error: W00t?
}
Answered By: Anonymous

Related Articles

  • What are the nuances of scope prototypal /…
  • What is the scope of variables in JavaScript?
  • What does this symbol mean in JavaScript?
  • Difference between variable declaration syntaxes in…
  • How to properly do JSON API GET requests and assign…
  • How to write dynamic variable in Ansible playbook
  • How to use html template with vue.js
  • How to access parent scope from within a custom…
  • 'this' vs $scope in AngularJS controllers
  • The 'compilation' argument must be an instance of…
  • How to parse JSON with XE2 dbxJSON
  • why does $http baddata occur. i need to authenticate user
  • What does "Fatal error: Unexpectedly found nil while…
  • Azure Availability Zone ARM Config
  • Reference — What does this symbol mean in PHP?
  • Simple Popup by using Angular JS
  • mongodb group values by multiple fields
  • error LNK2005: ✘✘✘ already defined in…
  • Javax.net.ssl.SSLHandshakeException:…
  • How can I throw CHECKED exceptions from inside Java…
  • What is a NullReferenceException, and how do I fix it?
  • Binding complex object to a component
  • Search match multiple values in single field in…
  • no match for ‘operator
  • Define a global variable in a JavaScript function
  • Event Snippet for Google only shows one event while…
  • How to get evaluated attributes inside a custom directive
  • Avoid creating new session on each axios request laravel
  • Created variable inside for loop can't be accessed…
  • How to detect JS frameworks/libraries used in a page?
  • Sorting A Table With Tabs & Javascript
  • Bind data based on the drop down selection from JSON…
  • loop and eliminate unwanted lines with beautiful soup
  • What is the copy-and-swap idiom?
  • How do you use script variables in psql?
  • How to do paging in AngularJS?
  • NullpointerException error while working with…
  • "No such file or directory" error when executing a binary
  • Most effective way to parse JSON Objects
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How find a file with part of his name in PowerShell
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Why does this Azure Resource Manager Template fail…
  • Overloading operators in typedef structs (c++)
  • What is the difference between '@' and '=' in…
  • How to traverse the complex nested Json in C# and…
  • IOException: read failed, socket might closed -…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • How do I limit the number of digits from 6 to 4 in…
  • Smart way to truncate long strings
  • ./components/Avatar.tsx Error: Cannot find module…
  • Injecting $scope into an angular service function()
  • What is The Rule of Three?
  • Node.js Best Practice Exception Handling
  • Octave using 'for' statement to show two animations…
  • Controller not a function, got undefined, while…
  • How to implement an STL-style iterator and avoid…
  • How can I pass a wct test while rearranging children…
  • AngularJS: ng-repeat list is not updated when a…
  • Does moment.js allow me to derive a timezone…
  • Azure CLI - az deployment group create -…
  • How to use Servlets and Ajax?
  • What's the correct way to communicate between…
  • What are the undocumented features and limitations…
  • How do I use $scope.$watch and $scope.$apply in AngularJS?
  • How does the "this" keyword work?
  • Fastest way to iterate over all the chars in a String
  • Wait until all promises complete even if some rejected
  • addEventListener() and removeEventListener() in loop…
  • Can't upload files with Apollo-client GraphQL in…
  • Angular 12 - Generating browser application bundles…
  • C++ OpenGL stb_image.h errors
  • Django - update inline formset not updating
  • Working with global window variable in mocha js from node
  • Swift do-try-catch syntax
  • Start redis-server with config file
  • What is an IndexOutOfRangeException /…
  • For-each over an array in JavaScript
  • C# Get YouTube videoId from Json
  • C++ template,typename and operator
  • How to download images without displaying them using Vue.js?
  • What should I do if the current ASP.NET session is null?
  • How to use Polymer 2 Build Process?
  • Python JSON TypeError : list indices must be…
  • How to create module-wide variables in Python?
  • How to unset a JavaScript variable?
  • What is an optional value in Swift?
  • How do I check if a type is a subtype OR the type of…
  • dynamically plot multiple variables in shiny dashboard R
  • Calculator: Back key doesnt work in Javascript
  • I am trying to subtract but it is always adding one…
  • Problems with local variable scope. How to solve it?
  • What's the difference between binding to [[var]] and…
  • error NG6002: Appears in the NgModule.imports of…
  • Python scrape JS data
  • How to choose the right bean scope?
  • Detecting an undefined object property
  • "Thinking in AngularJS" if I have a jQuery background?
  • Programmatically Lighten or Darken a hex color (or…
  • Typescript Symbol.species typing inference

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:

jQuery scroll to element

Next Post:

How do I tell if a regular file does not exist in Bash?

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