Reputation: 1257
I've seen this hovering around some javascript for a while now and was wondering what it meant.
In this code:
var topics = {};
jQuery.Topic = function( id ) {
var callbacks,
topic = id && topics[ id ];
if ( !topic ) {
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id ) {
topics[ id ] = topic;
}
}
return topic;
};
why does the variable topic have id &&
before it?
Upvotes: 0
Views: 76
Reputation: 437336
The &&
operator results in its first operand if it is "falsy" and to the second operand if the first operand is not "falsy". So, you could read this code as:
Let topic be
topics[id]
if this function was given a parameter¹, orundefined
if not.¹ Passing
false
or0
or other falsy values as a parameter would causetopic
to get that value, but reading the code does not leave the impression that you are supposed to do that.
Upvotes: 2
Reputation: 324620
What that line is doing is ensuring that id
is a truthy value before attempting to use it. It's probably not a good idea here, as it would make topics[0]
inaccessible.
The line topic = id && topics[id]
is roughly equivalent to if( id) topic = topics[id]; else topic = id;
Upvotes: 1