Logical Not before a Method

This is a function that tests if the array contains only factors of the provided number. What exactly is the purpose of logical not before the find method below and how does it essentially accomplish the same thing as return factors.every(x => num % x === 0);

function checkFactors(factors, num) {
	return !factors.find(n => num % n)

Example tests:

checkFactors([2, 3, 4], 12);
checkFactors([1, 2, 3, 8], 12);


Think about what the num % n is doing here. The find method will return the first element where the callback function returns a value of true. If num % n is equal to 0, which is falsy, then nothing gets returned. As soon as num % n does not equal to 0, which means there is a remainder and therefore a number was found that is not a factor of num, this elem is returned. The ! will toggle a Boolean value to its opposite, so true becomes false and false becomes true.

If a value is returned, that means it is not a factor, so the 8 in the second example will result in a remainder of 4. All numbers greater than 0 are truthy, so true gets returned by the find method and the ! converts it to false.

If none of the elements of the array result in the callback returning true, then the method returns the value undefined, which is a falsy value, so the ! converts the value false to true.


FYI - There is an edge case that the return !factors.find(n => num % n) will not get correct.

In the following example, it should return true incorrectly. No number can be divided by 0. 0 is not a factor of any number.

checkFactors([1, 2, 0, 3], 12);

The filter method would still handle this case correctly.