Understanding Parameters

  • Functions can have zero, one or more parameters. You can think of these as input that the function receives, and then uses to do something.

    The code example shows a trivial function multiply function that takes two numbers as arguments and returns their product.

    Do you remember how volume is defined? Complete the definition of the volume function.

    Show hint

    Recall that volume is calculated by multiplying an object's width, length, and height.

  • Just like in math, a function can take multiple arguments. When we define a function, we give each parameter a name. For example, I've named the cube function's single argument x.

    When you call a function, you don't need to know the parameter names. To show this, go ahead and change the name of the parameter in the cube function from x to n.

    Now of course that means that you have to change it everywhere it's used inside the function too. So you'll need to change line 2 to read return n * n * n; as well.

    Run the code after you've changed the parameter name to verify that the call cube(5) is not impacted at all by this change. It should still output the same result.

  • We just saw that the naming of parameters doesn't impact the caller of a function. In Javascript (and unlike languages such as Java), you also don't need to specify a type when defining a function.

    This means that when someone else calls your function, they can supply any type of argument that they want to – a number, a string, an array, etc.

    This can lead to strange behavior. If your function only works with, say numbers, such as the cube function, you may get strange results when it is called with a string.

    To check that, run the code as is. You will see that the returned value is NaN, which stands for not a number. That happens to be the value returned when we try to multiply a string three times with itself, in the return x * x * x; statement.

  • Now let's say we want to make sure that the caller always gets a numeric value back, even if the input wasn't of the right type.

    To achieve that, we need to check the type of the argument that was passed in. If it wasn't a number, we probably shouldn't try to multiply it. We'll just return 0 in that case.

    Uncomment line 2 to see that this works.

Keyboard shortcuts: Run CTRL + Enter Reset CTRL + S