Skip to content

J050 Usage of Functions

An assignment exploring different ways to declare functions in ES (ECMAScript).

Within your app.js:

Function Declarations

  • You’ll be creating two functions in three different ways. Both functions should take a price and a VAT percentage as their arguments.

    • One function returns the price inclusive of VAT: price * (1 + vatPercentage).
    • The other function returns the price exclusive of VAT: price / (1 + vatPercentage).
  • Create priceWithVAT1 and priceWithoutVAT1 as regular function declarations (function name(...) {}).

  • Create priceWithVAT2 and priceWithoutVAT2 where the function references are stored in a const (const x = function(...) {}).
  • Create priceWithVAT3 and priceWithoutVAT3 as arrow functions where the references are stored in a const (const x = (...) => ...).

Invoke all of these functions and print their results to the console to ensure they work. If priceWithVAT is called with arguments 100 and 0.25 (representing 25% VAT), and priceWithoutVAT is called with arguments 100 and 0.25, the printed results should be:

125
80
125
80
125
80
Solution
"use strict";

// Regular function declarations
function priceWithVAT1(price, vatPercentage) {
    return price * (1 + vatPercentage);
}

function priceWithoutVAT1(price, vatPercentage) {
    return price / (1 + vatPercentage);
}

// Functions with references in a const
const priceWithVAT2 = function(price, vatPercentage) {
    return price * (1 + vatPercentage);
}

const priceWithoutVAT2 = function(price, vatPercentage) {
    return price / (1 + vatPercentage);
}

// Arrow functions with references in a const
const priceWithVAT3 = (price, vatPercentage) => price * (1 + vatPercentage);

const priceWithoutVAT3 = (price, vatPercentage) => price / (1 + vatPercentage);

console.log(priceWithVAT1(100, 0.25));
console.log(priceWithoutVAT1(100, 0.25));
console.log(priceWithVAT2(100, 0.25));
console.log(priceWithoutVAT2(100, 0.25));
console.log(priceWithVAT3(100, 0.25));
console.log(priceWithoutVAT3(100, 0.25));

This script demonstrates various ways to declare and use functions in JavaScript.