Javascript Should I store a reference to a nested object or use it directly?
That depends almost entirely on the specific situation. In general, write whatever code is clearest, rather than worrying about efficiency, until/unless you have a performance problem in front of you that you need to solve.
Re your first snippet:
Accessing properties on objects takes non-zero time, but it's very efficient on modern browsers. So using ref
instead of a.b.c.d
will be faster, but it's unlikely to matter in any code you're writing unless you're doing it hundreds of thousands of times in a row in a tight loop. Worry about that if and when you're doing that.
The other thing to consider is whether other code may modifiy a
, or b
, or c
, such that ref === a.b.c.d
is no longer true. If you want your code to see those changes, don't use ref
. If you want it protected from such a change, use ref
, even though ref
may be out of date.
Re your second snippet:
There's a big difference: You're not calling getObject
later if you use ref
instead. If you know that you want to keep using the object getObject
returned to you initially, and/or you want to avoid the overhead of repeating the call, use ref
. But presumably getObject
exists for a reason, so in some cases it may make more sense to use getObject
again. It really varies depending on the details of the situation.