0

Can someone explain why the following code only works when I put beerCount-1 in parentheses? I'm really confused.

var beerCount = 99
function beer(){
    while (beerCount>0) {
        console.log(beerCount + " of beer on the wall. " + beerCount + " of beer. Take one down, pass it around, " + (beerCount-1) + " of beers on the wall.");
        beerCount--;
    }
}

beer()
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • 1
    it's because JS understands it as a function and it tries to call it. See this post to understand a bit more https://stackoverflow.com/questions/35949554/invoking-a-function-without-parentheses – LuisEgan May 15 '20 at 20:35

1 Answers1

2

+ and - have the same operator precedence: 14, and they both evaluate left-to-right.

When a string is +d with anything else, the resulting operation is concatenation: the other side, if it isn't a string, is coerced with a string. (If both sides are numbers, the resulting operation is addition)

But only numbers can be -d from each other. If something on one side of the - can't be coerced to a number, NaN will be the result.

So, with

"someString " + (beerCount-1) + " someOtherString"

The parentheses ensure that the middle expression gets evaluated first:

"someString " + someNumber + " someOtherString"

Without it, due to left-to-right operations, you get:

"someString " + beerCount - 1 + " someOtherString"
// ^^^^^^^^^^^^^^^^^^^^^^ evaluate first
"someString 99" - 1 + " someOtherString"
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluate second, but cannot subtract;
// "someString 99" cannot be coerced to a number, so result is NaN
NaN + " someOtherString"

which doesn't work.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320