In javascript, any other way of doing this is just hiding the fact that, under the hood, they are just doing exactly what your code already does.
For example, you could filter your array, and check whether it's length is >=
1
var userExists = database.user.filter(u => u.username === username).length >= 1;
It's shorter, and arguably a little more readable than your original, but its not necessarily best, and neither is it likely to be faster.
Slightly better would be to use find
- as this returns as soon as an element matches, meaning the whole array is not evaluated
var userExists = database.user.find(u => u.username === username) !== undefined;
(some
would also be appropriate)
Note, this answer uses ES6 format for lambda expressions, the equivalent in unsupporting browsers would be
var userExists = database.user.filter(function(u) {return u.username == username;}).length >= 1
// or
var userExists = database.user.find(function(u) {return u.username == username;}) !== undefined;
some
method – hindmost Jul 25 at 8:49database
in your code? – Jamiec Jul 25 at 8:51