30 Days Of JavaScript

Day 6: Functions Part 2

Lesson 1: Default arguments

As we learned yesterday, the arguments that are passed into a JavaScript function are positional. You need to call the function with the values you want for each argument in the correct position, otherwise when those values are used inside the function, they will be mixed up.

Here's a reminder:

In the code above you can see we pass in "1", "2", "3" and then "2", "1", "3". Depending on what this function did with the values, that second one could be the wrong way round.

The order and position of the arguments you pass into a function matter.

You can make arguments sort of optional though if you want. This means you don't have to include them in the call, however since the order and position matter, it is only possible to do this after your required arguments.

Let's look:

You can see here that when we declare the function we have an argument called optionalArg that we set to "4" as default in the declaration optionalArg = "4".

When we call the function for the first time we see "4" printed, as we don't provide an argument in that position.

In the second call we put the string "Hello" in that 4th position, so in that case the default is ignore and we see Hello printed out instead.

This isn't a commonly used feature of the language, however it's important to understand because it highlights the positional nature of the arguments in a JavaScript function call.

What do you think happens if we declare a function like this function showPositions(firstArg, secondArg, thirdArg, optionalArg = "4", fifthArgument) { and then call it with only 4 arguments?

Give it a try in the playground below, I've not completed all the code for you


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co