0

I'm not sure I understand the difference between (quotes around function name):

Template.year.helpers({
  'QueryHeader': function() {
    return Session.get('keyQueryHeader') + ' Attendees';
  }
});

and:

Template.year.helpers({
  QueryHeader: function() {
    return Session.get('keyQueryHeader') + ' Attendees';
  }
});

My IDE mentions something about a primitive value returned from constructor will be lost if when called with "new" if I don't use the quotes around the function name. If I use the quotes, it doesn't give me the warning. Both ways of writing the helper seem to do what they should. Should I use quotes around the name?

flimflam57
  • 1,334
  • 4
  • 16
  • 31

2 Answers2

1

When using quotes you can have names what contain special characters, spaces, etc:

var a = {
  'hello world': 'works!'
}

While this will throw Uncaught SyntaxError: Unexpected identifier

var a = {
  hello world': 'breaks'
}

See What characters are valid for JavaScript variable names?

The reason your IDE mention constructors is because there is a convention about writing constructors with uppercase first letter:

var myFunc = function() {};
var MyCons = function() {};

var myCons = new MyCons();
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

The interested helper QueryHeader returns Session.get('keyQueryHeader') + ' Attendees', which is a primitive value of most likely type string. It's absolutely fine to return a string from a function. However, the function starts with a capital letter 'Q' and your IDE treats the function as a class constructor when it is not surrounded by quotes. In this case, the returned value from the constructor is the created instance regardless of what primitive value is specifically returned. For this your IDE gives the warning primitive value returned from constructor will be lost.

Simply put, I believe the following snippets match the behavior of your IDE.

// This gives the warning.
var s = {
    S: function() { return 'some string'; }
};

// These don't.
var s = {
    'S': function() { return 'some string'; }
};

var s = {
    S: function() { return {}; }
};

var s = {
    'S': function() { return {}; }
};
Season
  • 4,056
  • 2
  • 16
  • 23
  • I see. So if I called the constructor with 'new', the string value is lost. If it returns an array or object (non-primitive value), the value isn't lost? – flimflam57 May 28 '16 at 13:38