Languages

JavaScript - how to fix the logic to check if one variable is greater than the other?

3 points
Asked by:
Kadeem-Craig
486

I have the following issue, I want to checkĀ if a customer is qualified for a promo.

// ONLINE-RUNNER:browser;

let promo = 100;
let itemInCart = 200;

let promoCheck = promo >= itemInCart ? 'Qualified' : 'Unqualified ';
console.log(promoCheck);

I tried the solution above and the customer may spend 200 and still not get qualified.

How would you solve the problem?

1 answer
3 points
Answered by:
Kadeem-Craig
486

There is wrong understanding of variables in this example.

To check if the customer is qualified for promo, we need to check if itemInCart has greater value than promo. If the customer buys more than the promo value is, he will be qualified.

The solution is simple, we need to change greaterĀ than orĀ equalĀ to operator (>=) to theĀ less thanĀ orĀ equal operatorĀ (<=).

// ONLINE-RUNNER:browser;

let promo = 100;
let itemInCart = 200;

let promoCheck = promo <= itemInCart ? 'Qualified' : 'Unqualified ';
console.log(promoCheck);

or swap the places ofĀ promo and itemInCartĀ variables in the statement

// ONLINE-RUNNER:browser;

let promo = 100;
let itemInCart = 200;

let promoCheck = itemInCart >= promo ? 'Qualified' : 'Unqualified ';
console.log(promoCheck);

we can also use if statement

// ONLINE-RUNNER:browser;

let promo = 100;
let itemInCart = 200;

let promoCheck = "Unqualified";

if (itemInCart >= promo) {
  promoCheck = "Qualified";
}

console.log(promoCheck);

Ā Note:

if statement it's easier to understand for beginners, however it generates more code. When you get better in coding you can useĀ conditional (ternary) operatorĀ (?) instead.

0 comments Add comment
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join