Trent Scott
Trent Scott

Reputation: 2028

JavaScript Conditional Statement Not Working

What's wrong with this JavaScript?

var numPackages == 0;

if (coffeeProducts <= 12) {
  numPackages == 1;
} else if (coffeeProducts % 12 == 0) {
  numPackages == coffeeProducts/12;
} else {
  numPackages == (coffeeProducts/12) + 1;
}

Basically, it needs to calculate the number of boxes/packages necessary to ship an amount of items (12 per box). Is there a better way to do this, perhaps using round()?

Upvotes: 0

Views: 290

Answers (4)

therealszaka
therealszaka

Reputation: 453

== is condition.

= is assignment.

The better way is to use Math.ceil() to round to next integer.

So:

var numPackages = Math.ceil(coffeeProducts/12);

Upvotes: 5

Richard A.
Richard A.

Reputation: 1157

Single equals (=) for assignment: x = 10

Double equals (==) for comparison: if (x == 10)

Triple equals for special cases where type is important as well as the value.

Change your two numPackages lines to a single equals and you're good to go :)

Upvotes: 1

bukart
bukart

Reputation: 4906

All the others explained your mistake with the comparing operator == and the assigning operator =.

The shortest way to solve it would be

var numPackages = Math.ceil( coffeeProducts / 12 );

Upvotes: 3

Phil
Phil

Reputation: 1929

Make each statement look like this:

if (coffeeProducts <= 12) {
    numPackages = 1; // just "=", not "=="
}

Upvotes: 1

Related Questions