Are side-effects in Array’s “every”, or “some” bad?

I’ve always been taught that having side-effects in an if condition are bad. What I mean is;

if (conditionThenHandle()) {
    // do effectively nothing
}

… as opposed to;

if (condition()) {
    handle();
}

… and I understand that, and my collegues are happy because I don’t do it, and we all go home at 17:00 on a Friday and everyone has a merry weekend.

Now, ECMAScript5 introduced methods like every() and some() to Array, and I find them very useful. They’re cleaner than for (;;;)‘s, give you another scope, and make the element accessible by a variable.

However when validating input, I more-often-than-not find myself using every/some in the condition to validate the input, then use every/some again in the body to convert the input into a usable model;

if (input.every(function (that) {
    return typeof that === "number";
})) {
    input.every(function (that) {
        // Model.findById(that); etc
    }
} else {
    return;
}

… when what I want to be doing is;

if (!input.every(function (that) {
    var res = typeof that === "number";

    if (res) {
        // Model.findById(that); etc.
    }

    return res;
})) {
    return;
}

… which gives me side-effects in an if, condition, which is bad.

In comparison, this is the code would look with with an old for (;;;);

for (var i=0;i<input.length;i++) {
    var curr = input[i];

    if (typeof curr === "number") {
        return;
    }

    // Model.findById(curr); etc.
}

My questions are:

  1. Is this definitely a bad practice?
  2. Am I (mis|ab)using some and every (should I be using a for(;;;) for this?)
  3. Is there a better approach?

8

If I understand your point correctly, you seem to be mis-using or abusing every and some but it’s a little unavoidable if you want to change the elements of your arrays directly. Correct me if I’m wrong, but what you’re trying to do is find out if some or every element in your sequence exhibits a certain condition then modify those elements. Also, your code seems to be applying something to all items until you find one that doesn’t pass the predicate and I don’t think that’s what you mean to be doing. Anyways.

Let’s take your first example (slightly modified)

if (input.every(function (that) {
    return typeof that === "number";
})) {
    input.every(function (that) {
        that.foo();
    }
} else {
    return;
}

What you’re doing here actually goes a little against the spirit of the some/every/map/reduce/filter/etc concepts. Every isn’t meant to be used to affect every item that conforms to something, rather it should only be used to tell you if every item in a collection does. If you want to apply a function to all items for which a predicate evaluates to true, the “good” way to do it is

var filtered = array.filter(function(item) {
    return typeof item === "number";
});

var mapped = filtered.map(function(item) {
    return item.foo(); //provided foo() has no side effects and returns a new object of item's type instead.  See note about foreach below.
});

Alternatively, you could use foreach instead of map to modify the items in-place.

The same logic applies to some, basically:

  • You use every to test if all elements in an array pass some test.
  • You use some to test if at least one element in an array passes some
    test.
  • You use map to return a new array containing 1 element (which
    is the result of a function of your choice) for every element in an
    input array.
  • You use filter to return an array of length 0 < length < initial array length elements, all contained in the original array and all
    passing the supplied predicate test.
  • You use foreach if you want map but in-place
  • You use reduce if you want to combine the results of an array in a single object result (which could be an array but doesn’t have to).

The more you use them (and the more you write LISP code), the more you realize how they are related and how it’s even possible to emulate/implement one with the others. What’s powerful with these queries and what’s really interesting is their semantics, and how they really push you towards eliminating harmful side-effects in your code.

EDIT (in light of comments):
So let’s say you want to validate that every element is an object and convert them to an Application Model if they’re all valid. One way to do this in a single pass would be:

var dirty = false;
var app_domain_objects = input.map(function(item) {
    if(validate(item)) {
        return new Model(item);
    } else {
        dirty = true; //dirty is captured by the function passed to map, but you know that :)
    }
});
if(dirty) {
    //your validation test failed, do w/e you need to
} else {
    //You can use app_domain_objects
}

This way, when an object doesn’t pass validation, you still keep iterating through the entire array, which would be slower than just validating with every. However, most of the time your array will be valid (or I should hope so), so in most cases you’ll perform a single pass over your array and end up with a usable array of Application Model objects. Semantics will be respected, side-effects avoided and everyone will be happy!

Note that you could also write your own query, similar to foreach, which would apply a function to all members of an array and returns true/false if they all pass a predicate test. Something like:

function apply_to_every(arr, predicate, func) {
    var passed = true;
    for(var i = 0; i < array.length; ++i) {
        if(predicate(arr[i])) {
            func(arr[i]);
        } else {
            passed = false;
            break;
        }
    }
    return passed;
}

Although that would modify the array in place.

I hope this helps, it was very fun to write. Cheers!

4

The side effects are not in the if condition, they are in the if’s body. You have only determined whether or not to execute that body in the actual condition. There is nothing wrong with your approach here.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật