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).
- One function returns the price inclusive of VAT:
-
Create
priceWithVAT1andpriceWithoutVAT1as regular function declarations (function name(...) {}). - Create
priceWithVAT2andpriceWithoutVAT2where the function references are stored in aconst(const x = function(...) {}). - Create
priceWithVAT3andpriceWithoutVAT3as arrow functions where the references are stored in aconst(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:
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.