Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    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.

    javascriptJavaScript
    Code

    Code

    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
    Transcript

    Transcript

    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.

    Discuss

    Discuss