Aditya Moon
Aditya Moon

Reputation: 13

Can someone explain why you need to put an integer variable and a number in brackets in a console.log?

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

Upvotes: 0

Views: 53

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

+ 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.

Upvotes: 2

Related Questions