1. Don't call your variable name
Try to call your variable something else, as name
is in many scenarios overwritten for other purposes. It's likely not the entire solution to your problem, but it can be a confounding factor moving forward, so I strongly advise against this variable name. I don't know what's a meaningful name in your use, so in my examples, I will simply call the variable x
.
2. Verify that the variable is being set
If your problem is that typeof x === 'undefined'
is always true, your first action should be to check the code where x
is being set. You haven't shown us any of this code. If you are indeed writing x = 123;
in an external file, throw in an alert(x);
immediately after that statement, to make sure that that specific piece of code is actually executing, and that the variable is being set according to your expectations.
3. Verify that your event listener is working
In your code, the code moves on to pass message if the variable is undefined. You're saying that the variable is always undefined. Could there be any other code that is calling pass message
? Throw in an alert(x)
here as well, to see that it really is entering the click listener, and that x
is undefined.
4. Check the scope of your variable
If alert(x)
did indeed show that x
was defined and had a value in your script, and a subsequent button click showed that x
was undefined (and you don't have any intermediate code saying anything like x = undefined
), you are almost certainly facing a scoping issue. Either the script that is assigning x
is writing to a local variable that is not accessible to your click listener, or the click listener is reading from a local variable that has priority over a global variable of the same name.
If you are sharing variables between separate scopes, you will need to rely on something that both pieces of code has access to, such as the global scope. If your external script executes window.x = 123;
instead, you will have a globally accessible variable named x
. In your click listener, you can test whether this is defined by the condition if(typeof window.x === 'undefined')