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()

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.