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?
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: