Objective

Create a function to add two values together whereby being provided with the values (as arguments) and with the appropriate ones is required, or otherwise an error gets thrown.

Difficulty

Easy

Description

If a function in a statically-typed language, such as C, C++ and Java, is set up with a given parameter and then if an argument isn't provided to the function for that parameter in the function's invocation, an error is raised.

This is why we generally say that statically-typed languages have a strict type system in place. For a function, if it is set to accept an argument, then it must be provided one at invocation.

JavaScript, however, isn't a statically-typed language and has very loosely-defined type rules.

Talking about functions in JavaScript, if a function is set up with a number of parameters, then it's perfectly alright to invoke the function without providing any arguments to it at all, as demonstrated below:

function sum(a, b) {
   return a + b;
}

sum(); // This is perfectly alright!

JavaScript won't throw any kind of errors. To make the parameters required, we ought to enforce this ourselves.

In this exercise, you have to define a function sum() that returns the sum of two given values, provided as arguments, when coerced into numbers.

It should work as follows:

  • If the function is called without two arguments, an appropriate error must be thrown.
  • If the arguments can't be coerced into a number, an appropriate error must be thrown. For instance, true converts to 1 and is therefore a valid value. In contrast, 'Hello' converts to NaN and is therefore an invalid value.