Simplify JavaScript collision detection with offset
Bug #1

Your code does not follow pattern (x - a &lt; y + b) &amp;&amp; (x + b + a &gt; y) but (x - a &lt; y + b1) || (x + b2 + a &gt; y) instead. So our refactored formula is moot! obsolete



Bug #2

A collision is detected when any of the guards trigger, not when all.



Proposed Solution

Solving both bugs, we could refactor Nikko Khresna's method:

function detectCollision(source, target, line) {
  return 
       source.location.x &lt; target.location.x + target.width + line
    || source.location.x + source.width + line &gt; target.location.x
    || source.location.y &lt; target.location.y + target.height + line
    || source.location.y + source.height + line &gt; target.location.y
  ;
}


and you can call it as follows

const collision = detectCollision(
  background.allPixels[i], background.allPixels[j], drawLineBetweenPixelRange);




Obsolete section because OP made a mistake in the formula: I'll keep it for historical reasons :)

Formula (Obsolete)

The way I see it, we could rewrite your expression:


var result = (x - a &lt; y + b) &amp;&amp; (x + b + a &gt; y)



as

var result = (x - a - b &lt; y) &amp;&amp; (x + b + a &gt; y)


and further as

var result = (x - (a + b) &lt; y) &amp;&amp; (x + (a + b) &gt; y)


now we can substitute (a + b) with offset

var result = (x - offset &lt; y) &amp;&amp; (x + offset &gt; y)


which means x and y have to be within offset distance of each other (|x-y| = abs(x-y))

var result = Math.abs(x - y) &lt; offset


Now you can substitute x, y and offset with your variables, and - as suggested in the other answer - use a method that calculates this collision for you.