JavaScript check if variable exists (is defined/initialized)

2,128,461

Solution 1

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?

Solution 2

You want the typeof operator. Specifically:

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

Solution 3

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

Solution 4

In JavaScript, a variable can be defined, but hold the value undefined, so the most common answer is not technically correct, and instead performs the following:

if (typeof v === "undefined") {
   // no variable "v" is defined in the current scope
   // *or* some variable v exists and has been assigned the value undefined
} else {
   // some variable (global or local) "v" is defined in the current scope
   // *and* it contains a value other than undefined
}

That may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):

if ("v" in window) {
   // global variable v is defined
} else {
   // global variable v is not defined
}

This, of course, assumes you are running in a browser (where window is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window is stylistically consistent with using window.name to refer to globals. Accessing globals as properties of window rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.

Solution 5

In the majority of cases you would use:

elem != null

Unlike a simple if (elem), it allows 0, false, NaN and '', but rejects null or undefined, making it a good, general test for the presence of an argument, or property of an object.


The other checks are not incorrect either, they just have different uses:

  • if (elem): can be used if elem is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).

  • typeof elem == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property.

    • This is the only check that won't throw an error if elem is not declared (i.e. no var statement, not a property of window, or not a function argument). This is, in my opinion, rather dangerous as it allows typos to slip by unnoticed. To avoid this, see the below method.

Also useful is a strict comparison against undefined:

if (elem === undefined) ...

However, because the global undefined can be overridden with another value, it is best to declare the variable undefined in the current scope before using it:

var undefined; // really undefined
if (elem === undefined) ...

Or:

(function (undefined) {
    if (elem === undefined) ...
})();

A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.

Share:
2,128,461
Samuel Liew
Author by

Samuel Liew

Useful Stack Overflow userscripts for everyone: Searchbar & Nav Improvements advanced search, search bookmarks, link to meta/main in sidebar Post Headers & Question Table of Contents sticky post headers and vote buttons, list of all answers in right sidebar Review Queue Helper skip audits, keyboard shortcuts, auto suggest close reason, auto focus dialog submit New Comments Layout better comment readability (username and date on a new line, etc.) Reduce Clutter hides many unnecessary things like podcast announcement banners, better duplicates revision list, strips analytics tracking from the site, fix broken avatar images Chat Improvements the only and best chat userscript To learn more about my userscripts, see the readme file on the repo. The Stack Exchange Timeline

Updated on April 12, 2022

Comments

  • Samuel Liew
    Samuel Liew about 2 years

    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) {
    
    • Admin
      Admin over 6 years
      if you want to know whether foo is declared, either typeof foo === 'undefined' or typeof foo === typeof undefined
    • Paul
      Paul almost 5 years
      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
    • oligofren
      oligofren almost 5 years
      @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
      oligofren almost 5 years
      @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.
  • Morgan Cheng
    Morgan Cheng over 15 years
    This looks a good solution, but can you explain why this works?
  • Jason S
    Jason S about 15 years
    @George IV: "just do `if( variable ) " -- um, no, that fails for false and 0.
  • scotts
    scotts about 14 years
    'if( variable )' also fails for testing for the existence of object properties.
  • Jerph
    Jerph over 13 years
    @staticsan: That's a good thing to consider, but many times you really only care if it's defined. E.g. an API you're using defines a variable that you're using only to check if the API is loaded.
  • squarecandy
    squarecandy over 12 years
    "if (typeof variable !== 'undefined') { // variable is not undefined }" is working for me too... thanks!
  • b01
    b01 over 12 years
    IE8 reported and error when I used: (typeof variable === "undefined" ), so I had to check for (typeof variable === "object" ) and that workded
  • skalee
    skalee over 11 years
    Why the latter is better in your opinion?
  • Cory Danielson
    Cory Danielson about 11 years
    I'm shocked that you can override undefined. I don't even think that's worth mentioning in the answer. Probably the single worst acceptable variable name in all of Javascript.
  • Eddie Monge Jr
    Eddie Monge Jr about 11 years
    This only checks if the variable was declared globally. If you are coding properly, then you are limiting your global vars. It will report false for local vars: (function() { var sdfsfs = 10; console.log( "sdfsfs" in window); })() `
  • Broxzier
    Broxzier almost 11 years
    @skalee I agree the latter is better. This for the simple reason that you check if the types are the ones you want before using them.
  • Alex W
    Alex W almost 11 years
    This causes an exception and requires you to use window. before the variable if used in the global context...this is not the best way.
  • temporary_user_name
    temporary_user_name over 10 years
    @anyone Why is this preferable to if (variable === undefined) {} ?
  • temporary_user_name
    temporary_user_name over 10 years
    This is the best f$#^%ing answer. I was at wit's end on this trying to figure out how to account for exactly this corner case. Brilliant. Had no idea you could do this.
  • Jim Puls
    Jim Puls over 10 years
    See a couple answers further down. The value undefined is mutable.
  • Wutaz
    Wutaz about 10 years
    The point is moot, because if varName is undefined then varName !== undefined will just cause a ReferenceError. The mutability of undefined won't matter.
  • Shog9
    Shog9 almost 10 years
    Heads-up: your answer has been migrated here from stackoverflow.com/questions/519145/…
  • Shog9
    Shog9 almost 10 years
    Heads-up: your answer has been migrated here from stackoverflow.com/questions/519145/…
  • Shog9
    Shog9 almost 10 years
    Heads-up: your answer has been migrated here from stackoverflow.com/questions/519145/…
  • Shog9
    Shog9 almost 10 years
    Heads-up: your answer has been migrated here from stackoverflow.com/questions/519145/…
  • Shog9
    Shog9 almost 10 years
    Heads-up: your answer has been migrated here from stackoverflow.com/questions/519145/…
  • Shog9
    Shog9 almost 10 years
    Heads-up: your answer has been migrated here from stackoverflow.com/questions/519145/…
  • john ktejik
    john ktejik over 9 years
    False. the latter throws an exception in my console.
  • Liglo App
    Liglo App over 9 years
    Because of this overriding issue you should ALWAYS use void(0) instead of undefined.
  • demisx
    demisx over 9 years
    Would be helpful to show inline the output of each alert.
  • Fred Gandt
    Fred Gandt about 9 years
    @demisx Agreed, but instead of suggesting the edit, why not just make it? The option is there for a reason. Some may consider it rude; I consider it efficient - so edited the answer myself (pending review).
  • Stephen P
    Stephen P almost 9 years
    @Fred - I looked at the edit history and can guess why your edits were rejected... rather than just adding lines to show what the output would be, as demisx suggested, you significantly changed what Jith had posted.
  • Christine268
    Christine268 almost 9 years
    As simple of JavaScript as this is I have NEVER used it but it serves my purpose beautifully. I have multiple .js files that run the same functions from a global js file, but only if a certain variable exists should certain functions run. Otherwise what I was doing is setting the variable to true or false and checking for that, but that would require me to address it on dozens of js files, so I needed another solution. Perfect!
  • Ilker Cat
    Ilker Cat over 8 years
    @Jason S "um, no, that fails for false and 0" -- um, yes, if you know that your variable cannot be false or 0 :)
  • qwertzguy
    qwertzguy over 8 years
    For Angular users: Unfortunately, it doesn't seem to be allowed in an ng-if statement.
  • Quicker
    Quicker over 8 years
    ...perfect blueprint for checks along scope. have you any performance indication, if "in window" or "(typeof variable === 'undefined' || variable === null)". Actually I am interested in a hard fact test and not in argumented potential rationale (which I could do myself: second clause has more operations -> worse performance)
  • Quicker
    Quicker over 8 years
    found one: andrew.hedges.name/experiments/in. looks like plain (variable === 'undefined') is faster than if-in. I think I write the author of that site to add a test for (typeof variable === 'undefined' || variable === null)
  • Mulan
    Mulan about 8 years
    typeof null; //=> "object"
  • Hp93
    Hp93 almost 8 years
    I don't think (variable === 'undefined') works. If you call a variable which is not declared, wouldn't it throw a ReferenceError? If there is a way to use this technique (property in window) for local scope, it would be great.
  • nikjohn
    nikjohn almost 8 years
    This fails when variable is null
  • CPHPython
    CPHPython almost 8 years
    This an awesome alternative and should be on the top upvoted of this question. Please simplify the answer headline with a working example that returns true (e.g. window.hasOwnProperty('console') or var hop = "p";window.hasOwnProperty('hop')).
  • CPHPython
    CPHPython almost 8 years
    No need to define a function for explaining, people will understand it immediately and a short answer is faster to read. If you still want to leave the snippet, just leave two lines on it, the first defining the var and the second printing the result.
  • Rob
    Rob over 7 years
    @StevenPenny Check the timeline. The top answer was merged from another question after this answer was posted
  • mpag
    mpag about 7 years
    the answer as it is flat out wrong. typeof variable always returns a string, thus is never false. e.g. if typeof(booooo) is "undefined" then typeof(typeof boooooo) is "string" and typeof boooooo && true is always true. @John-Slegers' answer is about as abbreviated as you can get with typeof.
  • RajeshKdev
    RajeshKdev about 7 years
    Its absolutely correct answer. Here is an working Fiddle. And i don't know which scenario you are talking about. The questions is about checking variable existence.
  • RajeshKdev
    RajeshKdev about 7 years
    @mpag Don't Say Flat wrong. Prove It. Finding a mistake is real easy, instead you can provide Good answers here!!!. If the answer is flat wrong 28 programmers wouldn't have up-voted without checking my answer. Since there are many reputed answers here they could have up-voted that, not this.
  • RajeshKdev
    RajeshKdev about 7 years
    Actually the second piece of code, is not to check same as above condition. I thought people would understand by this line If you wanted to check variable shouldn't be undefined or null., By this comment, its clearly stating, its not to perform the variable declaration check. that's to check variable value.
  • RajeshKdev
    RajeshKdev about 7 years
    Removed the typeof, which was misleading/gives the error. and updated this comment When the variable is declared, and if you want to check the value, this is even Simple, I hope this gives the clear answer.
  • RajeshKdev
    RajeshKdev about 7 years
    Thanks for making me correct my answer, Now, clearly we have condition to check JavaScript check if variable exists (is defined/initialized), And this answer is not flat out wrong anymore. ;)
  • mpag
    mpag about 7 years
    :) quite a bit improved. I'm not quite sure what you mean by "it would perform both checks together" as it's not checking if a variable is declared. It would be assigning a "null" string value if the first variable is declared but not defined.
  • Zelphir Kaltstahl
    Zelphir Kaltstahl about 7 years
    Finally something that does not throw an error because of accessing a member which does not exist … Something all the typeof answers simply overlook.
  • Zelphir Kaltstahl
    Zelphir Kaltstahl about 7 years
    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.
  • Fareed Alnamrouti
    Fareed Alnamrouti about 7 years
    your 2nd check will fail with 0 value
  • kwarnke
    kwarnke almost 7 years
    In newer Javascript versions undefined is an read only property. However to be bulletproof you can use typeof mvVar === typeof void 0. void 0 returns undefined always.
  • Thiago Yoithi
    Thiago Yoithi over 6 years
    Is the first case suitable when checking for an empty array too?
  • Alireza
    Alireza over 6 years
    @ThiagoYoithi, yes, you need to pass Array.length in this case which is 0 when it's empty, like if (myArray.length) {...}
  • Thiago Yoithi
    Thiago Yoithi over 6 years
    Yeah, but I would like to know the behavior in this approach: let arrayVar = []; if(arrayVar) // Is the result of this condition true, or false?
  • Alireza
    Alireza over 6 years
    @ThiagoYoithi in Javascript empty array [] is true, also empty object {}... because they are not values like 0, null, undefined etc... These are check for values... anyway good point to add it to my answer....
  • Thiago Yoithi
    Thiago Yoithi over 6 years
    @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 [].
  • Demonblack
    Demonblack over 6 years
    This is not what the OP asked. If data.url is equal to '' your solution would consider it undefined, when it is in fact defined as containing an empty string.
  • de3
    de3 over 6 years
    I agree is not what has been asked, and you are right: the empty string '' would be considered undefined. But I posted this because I thought it could be useful on the debate that has been created among different answers. And in the example, as well as in many other cases, you just want to print a string if there is actually content, so it's ok to take advantage of the fact the javascript considers falsy both empty string and undefined
  • tgf
    tgf over 6 years
    If you're on ES6 and your variable could be a const or let declared variable, there's a chance this code could fall in the temporal dead zone and throw ReferenceError. if (typeof variable !== 'undefined') { // the variable is defined }; const variable = 'a'; => ReferenceError
  • Adelin
    Adelin about 6 years
    This won't work with let or const. Here's why
  • TommyAutoMagically
    TommyAutoMagically almost 6 years
    +1 since this answer points out that sometimes you may actually want to identify false, 0, etc. as invalid values.
  • DerpyNerd
    DerpyNerd over 5 years
    Regarding the "check me please": This is correct because null and undefined are both "faulty" primitive types. They both represent "nothing" aka "void", so nothing != void is false
  • dRamentol
    dRamentol over 5 years
    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.
  • ropo
    ropo over 5 years
    I get a "ReferenceError: elem is not defined"
  • Alireza
    Alireza over 5 years
    @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...
  • Fanky
    Fanky about 5 years
    Then the answer is misleading when it says if(elem) checks for undefined (while it returns not defined error), isn't it?
  • Ry-
    Ry- about 5 years
    If you put it in a function, it’s redundant. typeof (x) != 'undefined' && x != null is equivalent to x != null when x is declared.
  • Armen Michaeli
    Armen Michaeli about 5 years
    This answer is outdated -- per standard ECMAScript you can define variables with let where these variables aren't available as properties of the window [or any other available] object. hasOwnProperty tests for presence of properties, not variables and thus cannot be used to detect variables defined by let.
  • Fred Gandt
    Fred Gandt about 5 years
    @amn The answer remains true regarding the use of var and is in that regard not outdated. I have however added a note outlining how the use of let and const differs from that of var. Thanks for your inspiration; together we rise :)
  • Armen Michaeli
    Armen Michaeli about 5 years
    Fred, that's an honest effort, thanks. If I were you, I'd put the cherry on top of the cake by mentioning explicitly that variables defined by let and const (the latter not truly variable) are not accessible as properties of any object and therefore the hasOwnProperty usage shown in the answer does not apply to these, for obvious reasons.
  • Fred Gandt
    Fred Gandt about 5 years
    @amn It is precisely because it is "obvious" and because there is no implication that let (or const) variables can be accessed by hasOwnProperty that I will leave the answer as is (although I will make a tiny note indicating that I mention const only for completeness ).
  • Fred Gandt
    Fred Gandt about 5 years
    @amn I have rewritten the answer (hopefully for the last time) to make more clear that hasOwnProperty can only be used in the prescribed manner to check for the existence of var variables. It reads okay to me.
  • Admin
    Admin almost 5 years
    Why does it not work with typeof variable !== undefined where the apostrophes is removed. Isn't window.undefined = 'undefined'?
  • Xitcod13
    Xitcod13 almost 5 years
    Tested the last case it works for undefined and null: codesandbox.io/s/lingering-lake-4cdfh
  • Fuseteam
    Fuseteam almost 5 years
    why not just variable != null it seems to catch "undefined" variables just as well
  • Jason
    Jason almost 5 years
    is this the "canonical way" that is portable?
  • Paul
    Paul almost 5 years
    This answer doesn't work. This is the only answer here that works: stackoverflow.com/a/36432729/772035
  • fogx
    fogx almost 5 years
    i agree with franky, this answer looks like it would solve ops problem, but it does not have the same effect as the other answers (which is checking if a value exists)
  • yiwen
    yiwen almost 5 years
    Unfortunately not working under IE 11. hasOwnProperty('indexedDB') always return false, for example even though indexedDB does exist
  • Fred Gandt
    Fred Gandt almost 5 years
    @yiwen I see that window.hasOwnProperty("indexedDB") returns false on IE11 while window.indexedDB returns the object. On Chrome, the same code returns true. IE11 however returns expected results for other checks (e.g. var foo="foo"; window.hasOwnProperty("foo"); returns true), so to say it's "not working" is not quite true. IE11 is clearly just being as temperamental as its ancestors.
  • yiwen
    yiwen almost 5 years
    A statement like "something is not working" is either true or false. As long as it fails in one case it qualifies as not working
  • yiwen
    yiwen almost 5 years
    Don't get me wrong, I like your method and I think it is very smart way to go. But before we can get rid of IE11 support, I, unfortunately, cannot use this method
  • oligofren
    oligofren almost 5 years
    This is wrong. bar=undefined is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist.
  • oligofren
    oligofren almost 5 years
    This is wrong. bar=undefined is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist.
  • oligofren
    oligofren almost 5 years
    This is wrong. window.bar=undefined is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist. If you did this.hasOwnProperty('bar') it might have worked.
  • oligofren
    oligofren almost 5 years
    This is wrong. window.bar=undefined is defined and set to a value. Your answer fails to detect the difference between this and if the variable does not exist. If you did this.hasOwnProperty('bar') it might have worked.
  • Cannicide
    Cannicide over 4 years
    This is a great answer. Local scope does not work, of course, because the in is checking for an object property "in" an object, in this case window. "Global variables" are those variables who are properties of the window object. To use non-global variables in this way, the window in the "myVariable" in window statement would have to be replaced with an object, and the local variable would have to be a property of some such object.
  • l00k
    l00k over 4 years
    === makes no sense here.. result of typeof is always string right? == 'undefined' is enough
  • almcaffee
    almcaffee over 4 years
    Give me a use case for checking if a variable is undefined and if is defined with an undefined value? Some of you are grasping at straws and attempting to look brilliant but if you are setting a value as undefined and checking for that value obviously it will return false or you need to change your code, smh.... this answer is correct!!!!!
  • mhenry1384
    mhenry1384 over 4 years
    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.
  • Melab
    Melab over 4 years
    What do you mean by "extract the code to a function"?
  • ha9u63ar
    ha9u63ar over 4 years
    this code doesn't work and you can verify this by using any browser console
  • user2878850
    user2878850 over 4 years
    Consider const x = 0; (() => console.log(x, this.hasOwnProperty('x')))();. Variable x is defined but false is returned...
  • john ktejik
    john ktejik about 4 years
    NOt correct. Doesn't catch completely undefined variables which is what the OP asked.
  • nacholibre
    nacholibre about 4 years
    (someUndefinedVariableName) fails with Uncaught ReferenceError: someUndefinedVariableName is not defined, so I think this answer is wrong.
  • johnsnails
    johnsnails about 4 years
    FYI, (a == b) placed onto Game of Life grid was not all that exciting.
  • phil294
    phil294 almost 4 years
    @l00k yes, both work here, but it makes more sense to rely on strict comparisons wherever possible and just try to treat == as nonexistent, as it provides not much besides confusion and error-proneness
  • l00k
    l00k almost 4 years
    @phil294 yeah I know that philosophy ;) but in my programmer history (more than 10 years) I still think - as far as you know what you are doing "==" is enough.
  • Maddy
    Maddy almost 4 years
    you can use !!ArrayName. This will return false if array is undefined or null. In case of empty array it will return true.
  • DanCat
    DanCat over 3 years
    is this a node construct and if so which version ... I was searching for exactly this and can't seem to find it ... JavaScript :shakesfirst:
  • BallpointBen
    BallpointBen over 3 years
    @Melab Ideally you could have function isDefined(x){...} and then call isDefined(myVar). But there is no way to safely pass a potentially undefined variable to isDefined because before the variable can be passed to the function, it must be evaluated, and if it doesn't already exist, then at that point it will throw (outside of the try/catch block, which is in the function). You have to evaluate the variable directly inside a try/catch block, so you cannot wrap the test in a function.
  • jcaron
    jcaron over 3 years
    This is quite wrong, this checks only whether the variable is truthy, not defined. !!0 is false even though 0 is defined.
  • asdf3.14159
    asdf3.14159 about 3 years
    This doesn't work for const or let variables
  • shrimpwagon
    shrimpwagon about 3 years
    This should be accepted answer. The typeof is useless if the variable has not been declared yet.
  • aross
    aross over 2 years
    While this is a good answer technically, it would be evidence of bad design if you truly require this.
  • user956584
    user956584 over 2 years
    if ( ("url" in req.body) == false && req.body.url.length > 1
  • Tom
    Tom over 2 years
    I agree here. I don't know why everyone is using strict equality when it's not necessary.
  • 12Me21
    12Me21 about 2 years
    yeah, this is technically correct, but impractically complex to write, when most of the time it doesn't matter if a variable is undeclared vs declared with a value of undefined
  • T Tse
    T Tse about 2 years
    window might not be defined if the js isn't run in a browser
  • Ben Aston
    Ben Aston about 2 years
    globalThis (added in ES2020) is a platform-independent mechanism for accessing the global object.
  • Aidan Welch
    Aidan Welch about 2 years
    @aross I disagree, if you are writing backwords compatible code- and certain JS implementations don't support things such as fetch() so you want to have a fallback
  • aross
    aross about 2 years
    @AidanWelch I don't understand what fetch has to do with anything. If you have code such as if (foo) { var bar = 123; } and then you proceed to do stuff with bar, you'll need to check whether bar exists to begin with. That is bad design which you should solve differently. Either you put the code that does stuff with bar in the if block, or you initialize bar at the top of your function somewhere so it's always defined.
  • Aidan Welch
    Aidan Welch about 2 years
    @aross If it is not a variable you are declaring but instead a standard object that may or may not exist in the environment you need to check if it exists.
  • catwith
    catwith about 2 years
    This is not true for variables declared with let and const instead of var. See: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • aross
    aross about 2 years
    @AidanWelch I think understand what you mean now. But in that case, typeof would be sufficient and you don't need the solution in this answer...... This answer is the only solution when you can have a variable with value undefined. So again, like I said, if you truly require this specific solution, that is evidence of bad design.
  • Aidan Welch
    Aidan Welch about 2 years
    @aross No typeof will still error, you need to use a try block
  • aross
    aross almost 2 years
    @AidanWelch I wouldn't know why typeof would error. Historically, typeof will always return a string. It's only recently that it can throw an exception, and that is f.ex. with the let keyword, when you try to use the variable before it's defined in the scope. And that doesn't apply in your situation.
  • Aidan Welch
    Aidan Welch almost 2 years
    @aross You're right actually, in my code it seemed like there was an error from it, but there must've been some other error, because going back to it now a few days later it does work.