How to check undefined variable in a ternary operator?
What is the best and short way to check if abc is undefined before accessing its properties as well as assign blank object {} if undefined?
And you said that
I am currently using (typeof abc !== "undefined")
Looks like you have abc defined and the value is undefined
.
You can try doing
var a = abc || {};
console.log(a);
state = (typeof state !== "undefined") ? state : '';
This way you can check undefined variable in a ternary operator.
while b and c throw ReferenceError when abc is undefined
So abc
isn't just undefined, it's undeclared. There's a big difference there.
If you need to handle abc
being undeclared, the only safe way to do that (without try
/catch
) is with typeof
:
typeof abc === "undefined"
That will be true, without error, if abc
is an undeclared identifier. It will also be true if abc
is declared and contains the value undefined
.
What is the best and short way to check if
abc
is undefined before accessing its properties as well as assign blank object{}
if undefined?
Probably using var
to ensure it's declared:
var abc = abc || {};
Duplicate var
declarations are not errors (duplicate let
declarations are). So with the above, if abc
is undeclared, it gets declared with the initial value undefined
and we assign it {}
. If it's declared, we replace its value with {}
if it's falsy. But, if it may or may not be declared with let
or const
, then the above will throw an error as well.
So to handle the case where it may or may not be declared with let
or const
, we need a different variable entirely:
let ourabc = typeof abc === "undefined" || !abc ? {} : abc;
That sets ourabc
to {}
if abc
is undeclared or if it contains a falsy value. Since all non-null
object references are truthy, and you've said you want to access object properties, that's probably the shortest way.