I am using Addy Osmani’s pub sub method:
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;
};
but before I add it to my project I’d like to understand it a little better. It’s fairly simple except for one line I’ve never seen: topic = id && topics[ id ];
topic = id ok. What is the && operator doing here? is it adding id to the topics array? or making a comparison?
should be read as
&&has an higher precedence, as stated on MDN documentationThe value assigned to
topicistopic[id]whenidis evaluated as “true” value,falseotherwise: so this is a shorter way for