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.
You could use the ternary operator to do this:
There is no way to get
o.pageto work on its own whenoisnull.Other ways exist, for example returning
{}instead ofnull, as calling nonexistent properties yieldsundefinedinstead 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.