|
| 1 | ++++ |
| 2 | +title = "This JavaScript condition is very strange..." |
| 3 | +date = 2025-03-28 |
| 4 | ++++ |
| 5 | + |
| 6 | +# This JavaScript condition is very strange... |
| 7 | + |
| 8 | +I was writing [this code](https://github.com/lfavole/lfavole.github.io/blob/1a7b1f5/content/blog/trigonometrie/trigonometrie.js#L153)... |
| 9 | +<div style="cursor: not-allowed; user-select: none"> |
| 10 | + |
| 11 | +```javascript |
| 12 | +class Fraction { |
| 13 | + // snip |
| 14 | + |
| 15 | + toString() { |
| 16 | + if (this.numerator === 0) |
| 17 | + return "0"; |
| 18 | + let result = ""; |
| 19 | + if (this.constructor.SYMBOL) |
| 20 | + if (this.numerator === -1) |
| 21 | + result += "-"; |
| 22 | + else |
| 23 | + result += this.numerator; |
| 24 | + result += this.constructor.SYMBOL; |
| 25 | + if (this.denominator !== 1) |
| 26 | + result += "/" + this.denominator; |
| 27 | + return result; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class PiFraction extends Fraction { |
| 32 | + static SYMBOL = "π"; |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +</div> |
| 37 | + |
| 38 | +but I quickly saw that it was doing the wrong thing, e.g. |
| 39 | +> `» new PiFraction(1, 4).toString()`<br> |
| 40 | +> `← "1π/4"` |
| 41 | +
|
| 42 | +which is not a fully simplified fraction. |
| 43 | + |
| 44 | +I ended up finding the error, which was: |
| 45 | +```javascript |
| 46 | +class Fraction { |
| 47 | + toString() { |
| 48 | + // snip |
| 49 | + if (this.constructor.SYMBOL) { |
| 50 | + if (this.numerator === -1) { |
| 51 | + result += "-"; |
| 52 | + } |
| 53 | + } else { |
| 54 | + result += this.numerator; |
| 55 | + } |
| 56 | + // snip |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | +which was what I meant when indenting the code, but the JavaScript compiler didn't understand it |
| 61 | +and compiled the nested conditional first. |
| 62 | + |
| 63 | +So if you write this: |
| 64 | +<div style="cursor: not-allowed; user-select: none"> |
| 65 | + |
| 66 | +```javascript |
| 67 | +if (a) |
| 68 | + if (b) |
| 69 | + c(); |
| 70 | +else |
| 71 | + d(); |
| 72 | +``` |
| 73 | + |
| 74 | +</div> |
| 75 | + |
| 76 | +Be careful, because it gets evaluated as: |
| 77 | +<div style="cursor: not-allowed; user-select: none"> |
| 78 | + |
| 79 | +```javascript |
| 80 | +if (a) { |
| 81 | + if (b) { |
| 82 | + c(); |
| 83 | + } |
| 84 | +else { |
| 85 | + d(); |
| 86 | +}} |
| 87 | +``` |
| 88 | + |
| 89 | +</div> |
| 90 | + |
| 91 | +and NOT as: |
| 92 | +```javascript |
| 93 | +if (a) { |
| 94 | + if (b) { |
| 95 | + c(); |
| 96 | + } |
| 97 | +} else { |
| 98 | + d(); |
| 99 | +} |
| 100 | +``` |
| 101 | +as you would expect it. |
| 102 | + |
| 103 | +The last code snippet is the only one that you should use. |
0 commit comments