27

I'm trying to test if a number is greater than 0 but less than 8. How do I do that in JavaScript?

This is what I'm trying:

if (score > 0 < 8) { alert(score); }
Magnus Lind Oxlund
  • 304
  • 1
  • 6
  • 19
veryserious
  • 305
  • 1
  • 4
  • 6
  • @ephemient can you explain it please how your code works? – tom May 01 '19 at 16:55
  • 2
    @tom Simple. `score>>>0` converts `score` to a non-negative integer. (Negatives become very large positive values due to two's complement representation.) If it is 8 or larger, `min` produces 8, bitwise and'ed with 7 to 0, a falsy value. If it is between 0 and 7, `min` changes nothing and neither does `&`, resulting in a falsy value of 0 or a truthy value between 1 and 7. – ephemient May 01 '19 at 19:25
  • @AlexejMagura Chained inequality notation has been in use in mathematics for centuries. How's that for tradition? (e.g., Paolo Ruffini's General Theory of Equations, 1799, p. 82) – Magnus Lind Oxlund Apr 03 '20 at 17:33
  • A related question: https://stackoverflow.com/q/6967573/1662230 – Magnus Lind Oxlund Apr 04 '20 at 15:58
  • A tangential question: https://stackoverflow.com/q/4090845/1662230 – Magnus Lind Oxlund Apr 04 '20 at 16:12

3 Answers3

49

Here's the code:

if (score > 0 && score < 8){
    alert(score);
}

P.S. This has nothing to do with jQuery. It's simple, naked JavaScript!

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
2
if ((score > 0) && (score < 8)) {
    alert(score);
}

But this is JavaScript, not jQuery.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

Query: Create a variable named score and set it to 8

Use console.log() that includes the string "Mid-level skills:" and compares the score variable to above 0 and below 10 using the && operator

Output :

var score = 8;
console.log("Mid-level skills:", score > 0 && score < 10)
Salwa A. Soliman
  • 695
  • 1
  • 3
  • 13
prachi
  • 1