Array.prototype.contains

Luke Hoban lukeh at microsoft.com
Thu Feb 23 22:15:44 PST 2012


>> From: es-discuss-bounces at mozilla.org [mailto:es-discuss-bounces at mozilla.org] On Behalf Of Peter Michaux
>>>> On Thu, Feb 23, 2012 at 12:35 PM, Mark S. Miller <erights at google.com> wrote:

>>>>     if (arr.contains(foo)) {
>>>>
>>>> vs
>>>>
>>>>     if (arr.indexOf(foo) !== -1) {

>> The readability of the above two options is very different. The first option is far superior as it expresses what the programmer wants to know. The second options is an expression of how it can be accomplished and requires understanding of indexOf's return values.

>> I think the addition Array.prototype.contains would be a good, simple one that would improve programs. The fact that this function exists in libraries means it is useful in a general in the opinion of at least several programmers.

Given that we are also already adding String.prototype.contains [1] in ES6, Array.prototype.contains seems a natural extension to continue keeping Array and String helpers aligned for common operations that are meaningful on both.  The argument to just use 'indexOf' would have been equally valid for String, but we had agreement that the usability/discoverability benefits of String.prototype.contains justified addition.  

Luke

[1] http://wiki.ecmascript.org/doku.php?id=harmony:string_extras 



More information about the es-discuss mailing list