5

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?

2
  • 1
    I don't think there are common 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. 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). Commented Feb 8, 2018 at 14:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.