Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 311
Josh Voigts Avatar asked Nov 20 '12 22:11

Josh Voigts


2 Answers

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.

like image 138
elclanrs Avatar answered Oct 20 '22 01:10

elclanrs


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 company 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 common 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.

like image 35
Undefined Avatar answered Oct 19 '22 23:10

Undefined