Skip to content
Home » JavaScript 27: Coalescence operator – application

JavaScript 27: Coalescence operator – application

function test() {
    let price = 3200;
    let isRegularCustomer = true;
    let numberofPurchases = 3;
    let discount = (numberofPurchases ?? 0) >= 3 ? 10 : 0;
    let totalPrice = price * ((100 - discount) / 100);
    console.log(`Bicycle price: ${totalPrice} €`);
}

JavaScript Tutorial: Calculating Customer Discounts Using the Ternary and Nullish Coalescing Operators

In this JavaScript exercise, we explore how to calculate the final purchase price of a bicycle based on the number of previous purchases made by a customer. Customers who have made at least three purchases receive a discount of 10%.

This exercise demonstrates how to combine conditional logic, the ternary operator, the nullish coalescing operator and arithmetic operations to implement a simple commercial business rule.

The JavaScript code

function test() {
    let price = 3200;
    let isRegularCustomer = true;
    let numberofPurchases = 3;

    let discount = (numberofPurchases ?? 0) >= 3 ? 10 : 0;

    let totalPrice = price * ((100 - discount) / 100);

    console.log(`Bicycle price: ${totalPrice} €`);
}

1. Declaring the variables

The program starts by declaring three variables:

let price = 3200;
let isRegularCustomer = true;
let numberofPurchases = 3;

The price variable represents the original purchase price of the bicycle, which is €3,200.

The isRegularCustomer variable is a Boolean indicating whether the customer is a regular customer.

The numberofPurchases variable represents the number of previous purchases made by the customer.

Although isRegularCustomer is declared, it is currently not used in the discount calculation. We will explore how to incorporate this variable later in the article.

2. Understanding the nullish coalescing operator

The nullish coalescing operator (??) provides a default value when a variable contains either null or undefined.

numberofPurchases ?? 0

If the number of purchases is available, JavaScript uses that value. Otherwise, it uses zero.

Original valueEvaluated value
33
55
00
null0
undefined0

This is particularly useful in commercial applications where customer information might be missing from a database or an external API.

3. Calculating the discount using the ternary operator

The discount is calculated using the following expression:

let discount = (numberofPurchases ?? 0) >= 3 ? 10 : 0;

The ternary operator is a compact alternative to an if...else statement.

Its general syntax is:

condition ? valueIfTrue : valueIfFalse;

In our example, JavaScript checks whether the customer has made at least three purchases. If the condition is true, the discount is 10%. Otherwise, the discount is 0%.

The equivalent code using a traditional conditional statement would be:

let discount;

if ((numberofPurchases ?? 0) >= 3) {
    discount = 10;
} else {
    discount = 0;
}

Both implementations produce exactly the same result.

4. Understanding operator precedence

The parentheses surrounding the nullish coalescing expression are important.

(numberofPurchases ?? 0) >= 3

They ensure that JavaScript first determines the number of purchases before performing the comparison.

Without these parentheses, JavaScript would evaluate the comparison 0 >= 3 before applying the nullish coalescing operator, potentially producing an incorrect discount. This demonstrates why understanding operator precedence is important when combining multiple JavaScript operators in a single expression.

5. Calculating the final purchase price

The final price is calculated using the following formula:

let totalPrice = price * ((100 - discount) / 100);

With an original price of €3,200 and a discount of 10%, the calculation becomes:

\[ 3200 \times \frac{100-10}{100} \]

\[ 3200 \times 0.9 = 2880 \]

Bicycle purchase summary

Original price

€3,200.00

Customer discount

10%

Total savings

€320.00

Final purchase price

€2,880.00

6. Displaying the result

The program displays the calculated price in the console using a template literal.

console.log(`Bicycle price: ${totalPrice} €`);

Template literals allow developers to embed variables directly into strings using the ${} syntax.

The expected console output is:

Bicycle price: 2880 €

8. Testing the discount calculation

From a software testing perspective, this exercise provides an excellent opportunity to practise boundary value analysis and equivalence partitioning.

The critical boundary is three purchases, because this is where the discount changes from 0% to 10%.

Test casePurchasesExpected discountExpected price
TC0100%€3,200
TC0220%€3,200
TC03310%€2,880
TC04410%€2,880
TC051010%€2,880
TC06null0%€3,200
TC07undefined0%€3,200

Testing the values immediately below, at and above the boundary helps verify that the discount is applied at the correct threshold.

9. Improving the implementation

The original program declares the isRegularCustomer variable without using it.

If the business requirement specifies that only regular customers with at least three previous purchases are eligible for a discount, we can introduce the logical AND operator (&&).

function test() {
    const price = 3200;
    const isRegularCustomer = true;
    const numberOfPurchases = 3;

    const discount =
        isRegularCustomer &&
        (numberOfPurchases ?? 0) >= 3 ? 10 : 0;

    const totalPrice = price * ((100 - discount) / 100);

    console.log(`Bicycle price: ${totalPrice.toFixed(2)} €`);
}

This improved version introduces several changes:

  • The logical AND operator ensures that both discount conditions must be satisfied.
  • The const keyword prevents accidental reassignment of variables.
  • The variable numberOfPurchases follows the conventional JavaScript camelCase naming convention.
  • The toFixed(2) method displays the price with two decimal places.

The expected output is:

Bicycle price: 2880.00 €

The additional regular customer condition represents a possible extension of the original business rule rather than a necessary correction. A production implementation should also validate purchase counts and prices and handle monetary rounding appropriately.

Conclusion

This JavaScript exercise demonstrates how several fundamental programming concepts can be combined to implement a practical business application. The nullish coalescing operator handles missing values, the ternary operator simplifies conditional logic, and arithmetic operations calculate the final purchase price. Understanding these concepts is valuable for developing commercial applications, including online shops, customer loyalty programmes, invoicing systems and automated pricing engines. Furthermore, by applying software testing techniques such as boundary value analysis, developers and software testers can verify that business rules behave correctly under different conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *