Default Parameters in JavaScript: Beginners Guide

Written by micogongob | Published 2021/05/15
Tech Story Tags: javascript | beginners | functional-programming | learning | learning-to-code | coding | software-development | basics

TLDR This article assumes you have some familiarity with coding in the JavaScript ecosystem. In this short article we will cover Function Defaults and learn how to use it in our day to day JavaScript programming. We learned how to set sane default values for the parameters in our JavaScript functions. You can also use function defaults one step further by using another parameter as the default. The product() function just squares the first parameter if the second one isn’t provided. The result is that your code just runs without the correct parameters.via the TL;DR App

In this short article we will cover Function Defaults and learn how to use it in our day to day JavaScript programming. This article assumes you have some familiarity with coding in the JavaScript ecosystem.

Function Defaults

Function parameters are weird in JavaScript, when you call a function in Java or C# without arguments, you get syntax errors. But when calling a function without providing parameters in JavaScript, your code just runs. This can result to your functions being called with incomplete inputs and that could introduce some bugs. You can counter this problem with defensive programming.
You can add some additional if statements or validations if a function’s parameters have the correct values. But having a lot of if statements for most of your functions could result to messy code. A better way for this is to use the ES6 feature where you can have function defaults. As the example code shows, you can simplify the validation of your function parameters by setting default values.
function sum(x=0, y=0) {
  return x + y;
}

console.log(sum());
// expected output: 0

Using Another Parameter as the Default

You can also use function defaults one step further by using another parameter as the default. In the code example below, the product() function just squares the first parameter if the second one isn’t provided.
function product(x, y=x) {
  return x * y;
}

console.log(product(3));
// expected output: 9

End

That is all. We used simple examples but we learned how to set sane default values for the parameters in our JavaScript functions, preventing unexpected behavior while keeping the code clean.

Written by micogongob | PH Software Engineer
Published by HackerNoon on 2021/05/15