user1554264
user1554264

Reputation: 1224

Unsure of what combining operators performs in function

I have been programming the following function and have understood everything up until this line.

   cost += nightSurcharge;

I am using conditionals in my if statement that are used to add the nightSurcharge to the cost between 8pm and 6am.

What I need to understand is whether the += is simply saying add the nightSurcharge to cost if the condition is met?

// add a parameter called hourOfDay to the function
    var taxiFare = function (milesTraveled, hourOfDay) {
      var baseFare = 2.50;
      var costPerMile = 2.00;
      var nightSurcharge = 0.50; // 8pm to 6am, every night

      var cost = baseFare + (costPerMile * milesTraveled);

      // add the nightSurcharge to the cost starting at 
      // 8pm (20) or if it is before 6am (6)
       if (hourOfDay >= 20 || hourOfDay < 6) {
          cost += nightSurcharge;
      } 

      return cost;

    };

Upvotes: 0

Views: 52

Answers (1)

Matt Ball
Matt Ball

Reputation: 359966

What I need to understand is whether the += is simply saying add the nightSurcharge to cost if the condition is met?

Yes, that is exactly correct. This code is equivalent:

if (hourOfDay >= 20) {
    cost = cost + nightSurcharge;
}
else if (hourOfDay < 6) {
    cost = cost + nightSurcharge;
}

Upvotes: 3

Related Questions