Jason Ip
Jason Ip

Reputation: 353

leaderboard example, confusion with 'selected_name' return value

In the leaderboard example, in leaderboard.html how come the call to {{selected_name}} returns the selected_name string but in the leaderboard.js file where the function is, it returns a boolean? I know this is more of a JS question but just trying to get my head wrapped around it

Upvotes: 0

Views: 88

Answers (1)

Peppe L-G
Peppe L-G

Reputation: 8345

You're thinking of the following code?

Template.leaderboard.selected_name = function () {
    var player = Players.findOne(Session.get("selected_player"));
    return player && player.name;
}

This does not return a boolean, although the &&-operator is a boolean operator. The "right way" would of course be to just have return player.name, but if Players.find returns null (no player with the selected id exists), this code would crash when executed. To avoid this from happening, the little hack with the &&-operator is used, which ensures that player.name is only executed if player is non falsye (not null). The result of the operator is the right hand side of it, so the name of the player is returned (or null, the left hand side of it, if it's null).

Upvotes: 2

Related Questions