Categories
function initialization javascript undefined variables

JavaScript check if variable exists (is defined/initialized)

2212

Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))

if (elem) { // or !elem

or

if (typeof elem !== 'undefined') {

or

if (elem != null) {

4

  • 12

    if you want to know whether foo is declared, either typeof foo === 'undefined' or typeof foo === typeof undefined

    – user719662

    Nov 22, 2017 at 21:00

  • 4

    The highly upvoted answers don’t work for variables that are declared but have the value undefined. The correct answer is this one: stackoverflow.com/a/36432729/772035

    – Paul

    Jul 23, 2019 at 22:50

  • 2

    @Paulpro, the version using hasOwnProperty('bar') doesn’t have the same deficiencies as the others, but would require some adjustment for Node (replace window with global).

    – oligofren

    Sep 24, 2019 at 6:17

  • @Paulpro Indeed, but as I was pondering that before you replied, I came to the conclusion that it’s not really a practical problem. When you are dealing with block or function scoped variables, it’s usually code you own or have write access to, so you’ll have a runtime error in any case which is fixable. Whereas the usual problem with variables that has not beed defined (doesn’t exist) usually lies in code outside of your control, so you need a way of detecting it. So it’s the 80/20 solution.

    – oligofren

    Sep 24, 2019 at 9:28

1036

The typeof operator will check if the variable is really undefined.

if (typeof variable === 'undefined') {
    // variable is undefined
}

The typeof operator, unlike the other operators, doesn’t throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

4

  • 3

    @StevenPenny Check the timeline. The top answer was merged from another question after this answer was posted

    – Rob

    Dec 19, 2016 at 23:25


  • Warning: This does not work for members of objects, if you try to access them using the dot notation as in some_object.a_member.

    May 17, 2017 at 8:19

  • this doesn’t check if a variable exists, it checks its value type. You want to check if a variable it’s been declared. @BrianKelley’s answer is the right one.

    – dRamentol

    Nov 15, 2018 at 19:12

  • why not just variable != null it seems to catch “undefined” variables just as well

    – Fuseteam

    Jul 8, 2019 at 20:30

1036

The typeof operator will check if the variable is really undefined.

if (typeof variable === 'undefined') {
    // variable is undefined
}

The typeof operator, unlike the other operators, doesn’t throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

4

  • 3

    @StevenPenny Check the timeline. The top answer was merged from another question after this answer was posted

    – Rob

    Dec 19, 2016 at 23:25


  • Warning: This does not work for members of objects, if you try to access them using the dot notation as in some_object.a_member.

    May 17, 2017 at 8:19

  • this doesn’t check if a variable exists, it checks its value type. You want to check if a variable it’s been declared. @BrianKelley’s answer is the right one.

    – dRamentol

    Nov 15, 2018 at 19:12

  • why not just variable != null it seems to catch “undefined” variables just as well

    – Fuseteam

    Jul 8, 2019 at 20:30

308

In many cases, using:

if (elem) { // or !elem

will do the job for you!… this will check these below cases:

  1. undefined: if the value is not defined and it’s undefined
  2. null: if it’s null, for example, if a DOM element not exists…
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false

So it will cover off kind of all cases, but there are always weird cases which we’d like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string… for example in this case you add one more check using trim(), like:

if(elem) {

if(typeof elem === 'string' && elem.trim()) {
///

Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.

I create the image below to show a quick brief of the answer:

undefined, null, etc

16

  • 2

    @Alireza, nice! Your answer will help a lot of people out there. I already memorized these falsy values, the only thing that I wasn’t sure was about [].

    Dec 1, 2017 at 20:01

  • 29

    I get a “ReferenceError: elem is not defined”

    – ropo

    Nov 19, 2018 at 10:05

  • 3

    @ropo, it’s because you even didn’t define the elem to check what it’s , if it’s your case, you need to check it with typeof(elem)===”string” which is mentioned already…

    – Alireza

    Nov 19, 2018 at 12:09

  • 44

    Then the answer is misleading when it says if(elem) checks for undefined (while it returns not defined error), isn’t it?

    – Fanky

    May 14, 2019 at 14:34

  • 7

    Surprised my the number of upvotes. The answer is simply wrong. As mentioned in comments above, “if (elem) {}” does not check for undefined, it will throw an error if the variable is not defined. However, “if (window.elem) {}” will not throw an error if elem is undefined.

    Nov 21, 2019 at 19:04