In Javascript, all function arguments are optional by default. That means if you ever forget to pass a critical parameter, the code will just fail without warning you what went wrong.
There are many
workarounds for this, and in this lesson, you will learn one of the easiest and foolproof methods of solving this problem.
Instructor: [00:00] Let's say we have a function named division, and it takes in two parameters, A and B, and just returns the division of the two numbers. Now, let's log the value by passing in only one of the parameters, and omitting the second parameter. Let's pass in 10.
[00:14] Now, if we run the file, you can see that the output is not a number. Ideally, to avoid such situations, we would like the function to throw an error when the second parameter is not passed. To tackle this situation, we'll make a function called require. Then we'll pass in a parameter as param.
[00:33] Then inside this, we'll throw a new error whenever the parameter that is required is not given, or not passed in the original function, it will throw an error. Here, we'll use template strings, pass in parameter, and then say that the parameter is not defined.
[00:48] Let's refactor our division function a little bit. We'll make A equal to required, and then pass in a string A. The string A will be representing our parameter A, the first parameter. Then B, for it to require string of B, where the string B represents the second parameter, B.
[01:09] Now, if we go ahead and run the file, you can see that it throws an error, and says that B is not define. Our require function works. Now, let's check if it works if both the parameters are passed.
[01:24] Let's just clear this, and pass in our second parameter as two. Now, if we run the file, the result should be five. It is five, as expected.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!