Reputation: 2673
I have a situation where I declare an object var o = null;
Then, I pass it into a function, do stuff and maybe assign an object to it.
Later on, I execute parse(o.page)
.
If o
is null, then I get "TypeError: o.page is null",
and the program stops there because I'm trying to get the property of a null value.
I know one solution could be to initially assign null to all of o
's properties.
Just wondering if there is a more subtle way to handle this error.
because I would like to handle parse1(o);
and parse2(o.page1)
where o
can be null.
Upvotes: 2
Views: 7051
Reputation: 338208
You could use the ternary operator to do this:
parse2(o ? o.page1 : null)
There is no way to get o.page
to work on its own when o
is null
.
Other ways exist, for example returning {}
instead of null
, as calling nonexistent properties yields undefined
instead of throwing an error.
Generally speaking, avoiding a situation where invalid calls linger in your code is recommendable. Either you check the return value before you use it (like above), or you don't return values that can invalidate subsequent code.
Upvotes: 3
Reputation: 270617
Instead of null
, assign an empty object.
var o = {};
You cannot assign a property to o
if it is null
. That would result in
TypeError: Cannot set property 'propname' of null
Upvotes: 2