How to Create Functions in JavaScript

Code Playground is only enabled on larger screen sizes.

The functions demonstrated in the previous lesson only accept one input argument, but in fact, JavaScript functions are pretty flexible about the number of arguments you give them.

It is possible to define a function that accepts multiple arguments, optional arguments, or even an indefinite number of arguments.

When the function must deal with multiple input arguments, you can separate them with commas.

For example, sum3() is a function that calculates the sum of three numbers.

javascript
let sum3 = function (num1, num2, num3) {
  return num1 + num2 + num3;
};

The function declaration syntax and the arrow function work similarly.

javascript
function sum3(num1, num2, num3) {
  return num1 + num2 + num3;
}
javascript
let sum3 = (num1, num2, num3) => num1 + num2 + num3;

This function requires three arguments. When you call the function with less than three arguments, the ones left out will be assigned undefined.

javascript
function sum3(num1, num2, num3) {
  console.log(`num1 is ${num1}`); // -> num1 is 1
  console.log(`num2 is ${num2}`); // -> num2 is 2
  console.log(`num3 is ${num3}`); // -> num3 is undefined
  return num1 + num2 + num3;
}
 
console.log(sum3(1, 2)); // -> NaN

If you pass too many arguments, the extra ones will simply be ignored.

This flexibility can be useful in practice, as it enables you to create functions that accept any number of arguments, but it does lead to problems sometimes.

For instance, in our previous example, JavaScript cannot calculate 1 + 2 + undefined, so it returns NaN, not a number.

To prevent this from happening, it is best to give the argument a default value.

javascript
function sum3(num1, num2, num3 = 0) {
  console.log(`num1 is ${num1}`);
  console.log(`num2 is ${num2}`);
  console.log(`num3 is ${num3}`);
  return num1 + num2 + num3;
}
javascript
console.log(sum3(1, 2));

This way, instead of undefined, num3 will be assigned 0 if a value is not provided when the function is called.