Reputation: 3674
In sample code of the yui library, I see this notation:
var obj = document.getElementById("coffee_msg");
obj.style.display = 'block';
As obj is only used once, I would rather prefer this:
document.getElementById("coffee_msg").style.display = 'block';
Is there any reason why the first notation is used in the yui library and many other places? Are there incompatibilities with certain browsers?
Upvotes: 1
Views: 121
Reputation: 150313
There isn't a "real" reason, just to make the code a little bit more readable.
Just like with:
var myAge = 26;
var myAgeNextYear = myAge + 1;
VS:
var myAgeNextYear = 26 + 1;
My personal preference is to keep a reference to the obj only if I'm using it more than once.
Upvotes: 2
Reputation: 1223
The first option is useful because it improves readability, it also makes the obj variable available immediately for other use. I would use this example personally.
Upvotes: 0
Reputation: 13351
The two different ways work exactly the same. Using a temporary obj
variable could be useful to improve readability of the code (but it should be given a name better than obj
in that case).
Upvotes: 2
Reputation: 318778
If you only need to set one property it doesn't matter at all (as long as you do not want to check if the return value is valid before trying to access a property of it).
However, if you have multiple properties you'll want to do the lookup only once (even though an id lookup is extremely fast), so assigning the element to a variable is the way to go in that case.
Of course you could make this even shorter with jQuery: $('#coffee_msg').show()
Also has the advantage that you do not get an error if the element does not exist for some reason. And if you want to set multiple CSS properties etc, you can simply use a function that does that for you with a single call or chain multiple calls to different jQuery methods.
Upvotes: 2