2

I would like to check to see wether a number is within 4 of a target number.

Currently I do this in the following manner:

DEMO: https://jsfiddle.net/o0b99yys/

var targetNum = 32;
var newNum = 31;

if ((newNum > (targetNum + 4)) || (newNum < (targetNum - 4))) {
  alert('Error: number must be within 4 or target');
} else {
  alert('Success: number is within 4 or target');
}

this seems a little amateurish. Is there a cleaner more professional way of doing this?

11
  • 8
    If it works, its professional Commented Dec 18, 2015 at 13:17
  • 9
    Math.abs(targetNum - newNum) < 4 like this? Commented Dec 18, 2015 at 13:17
  • 1
    This will do it: Math.abs(targetNum - newNum) <= 4 Commented Dec 18, 2015 at 13:19
  • 2
    @Pamblam no! it cant be bigger and also lower!!! There must be || Commented Dec 18, 2015 at 13:19
  • 3
    I don't know how this question can get upvotes at all. You have a 6 line code with a if-statement. I mean wtf could someone do wrong... Commented Dec 18, 2015 at 13:28

3 Answers 3

3

This solution looks better:

var targetNum = 32;
var newNum = 31;

if (Math.abs(targetNum - newNum) > 4) {
  alert('Error: number must be within 4 or target');
} else {
  alert('Success: number is within 4 or target');
}
Sign up to request clarification or add additional context in comments.

4 Comments

If you copy&paste the solutions of other people, please, try to explain it and format with code tools
I didn't copy anybody's solution, I posted it also in the comments.
Ok! Sorry if I disturb you.
Thanks, exactly the kind of elegant solution i was looking for.
1

    var targetNum = 32,
        newNum = 31,
        target_range_max = targetNum + 4,
        target_range_min = targetNum - 4;

    if ( target_range_min <= newNum && newNum <= target_range_max ) {
     alert('Success: number is within 4 or target');
    } else {
     alert('Error: number must be within 4 or target');
    }

Comments

0

try this if u want simplified versions on that expressions:

var myNum = 32;
var newNum = 31;

Math.abs(myNum-newNum)>4 ? alert('Error: number must be within 4 or target') : alert('Success: number is within 4 or target');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.