admin管理员组

文章数量:1391999

Is there a convention for naming mutable and predicate functions in Javascript?

For example, in Ruby, Lisp, etc., functions that mutate their contents, like gsub!, usually have an exclamation point as a convention to denote that the function is dangerous.

Or, if the function returns a boolean value, like even?, the function will have a question mark.

Unfortunately, you can't use special characters like ? or ! in function names in Javascript, so what conventions do Javascript programmers use to denote these special types?

Is there a convention for naming mutable and predicate functions in Javascript?

For example, in Ruby, Lisp, etc., functions that mutate their contents, like gsub!, usually have an exclamation point as a convention to denote that the function is dangerous.

Or, if the function returns a boolean value, like even?, the function will have a question mark.

Unfortunately, you can't use special characters like ? or ! in function names in Javascript, so what conventions do Javascript programmers use to denote these special types?

Share Improve this question asked Nov 20, 2012 at 22:14 Josh VoigtsJosh Voigts 4,1321 gold badge21 silver badges43 bronze badges 2
  • 1 I don't think there are mon conventions on that. Most functions try not to mutate their input, if they do it does get documented well and/or they are named very descriptive. – Bergi Commented Nov 20, 2012 at 23:29
  • Exclamation mark in Ruby methods doesn't mean they mutate their receiver. There's !-methods that don't mutate state(like find_by! in activerecord), and there's mutation functions that have no exclamation mark(e.g. Set#add). – RocketR Commented Feb 8, 2018 at 14:51
Add a ment  | 

2 Answers 2

Reset to default 6

Yes, the usual convention for naming a function that returns true|false is to prefix it with is, as in isDate, isHidden... As for methods that mutate there's no convention AFAIK, but in JavaScript most methods don't modify the original object, so you just need to know which ones do and which ones don't, but you'll be able to tell. For example replace doesn't modify the original object so you can tell because of the assignment: a = a.replace(...), but a method like splice does modify the original object, so you can tell because there's no assignment on the same variable.

There isnt really anything like this in JavaScript by default. It depends on the organisation you work for whether they have any coding conventions they keep to.

One convention which my pany follows is to prefix a function with a underscore to denote an internal variable/function. This would be equivalent to a private variable/function in OOP.

E.g One mon one I would use inside an controller in jMVC would be:

_isIE = $('html').is('.ie8, .ie9');

As we only want this to be accessible to other functions in that controller.

本文标签: coding styleIs there a convention for naming mutable and predicate functions in JavascriptStack Overflow