I have the below code:
if (typeof profileChart !== undefined) {
profileChart.destroy();
} else {
let profileChart = new Chart(
pisteElevationProfileChart,
configPiste
);
}
Despite the solution provided here, I still get an error as follows;
script.js?ver=1.0:336 Uncaught ReferenceError: profileChart is not defined
So how can you test for an undefined variable.
4
Answers
Here’s your problem:
The
typeof
value is never going to beundefined
. You need to check againsttypeof undefined
.Explanation:
This piece of code will evaluate to the string
"undefined"
if the variableprofileChart
is not defined.This statement will always evaluate to
True
.will evaluate to "undefined".
evaluates to
False
so theelse
block would be executed when the variable is not defined.Others explained the typeof issue.
The reference error you get when you do
if (profileChart)
is because you need to DECLARE the variable before you can test it for falsy values.You declare it and wrap it like this
The problem can be slightly deeper in the code. What is the line where you declare the variable and what keyword do you use (
var
,let
, orconst
)? The scope where you are declaring the variable also matters. If, for example, you declare a variable inside anif
statement (something like the following:), then the variable will never be accessible (ReferenceError is the error where variable has not been initialized yet and so it can’t be accessed for the type checking). The solution that can work here is:
Hope this is well, but it’s better to rearrange this sort of code in favor of the const declaration
the issue is that the
typeof
operator returns a string representing the type of the operand so when checking if a variable isundefined
you need to compare the result oftypeof
with thestring undefined
best approach would be to declare
profileChart
with an initial value of undefined outside of your if/else block.