Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Required function arguments in Javascript

    Akash GuthaAkash Gutha

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.