How do you make a parameter to expect a number or a string? (Example included)

As seen in excercise weight on different planets
FireShot Capture 002 - Code Challenges_ Javascript Fundamentals - Codecademy -
How do you expect a parameter to be a number or a string?

JavaScript is loosely typed and has no formal declaration of type when defining variables. That puts the onus on us to validate inputs to ensure they meet the function’s requirements.

We do have the typeof operator to help us determine data type, and instanceof to test if it is a member of a particular class. Each of these may have their own provisos and weaknesses.

if (typeof x === 'number') {}

if (! typeof x === 'number') {}
1 Like

It could be that the function needs one parameter to be a number such as with this:

function add(n) {
    return n + 7;

If you gave it a value that is not a number it would return an error.

1 Like

There would not be a return. JS will throw an error and halt the program.


Sorry, that is what I meant.
Thanks for correcting my terminology


I got it now. Thanks

1 Like