Kpower
Kpower

Reputation: 1257

Using the name of a variable and then defining a function for the variable

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

Answers (2)

Jon
Jon

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¹, or undefined if not.

¹ Passing false or 0 or other falsy values as a parameter would cause topic to get that value, but reading the code does not leave the impression that you are supposed to do that.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions