paint-brush
Default Parameters in JavaScript: Beginners Guideby@micogongob
279 reads

Default Parameters in JavaScript: Beginners Guide

by Mico GongobMay 15th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.
featured image - Default Parameters in JavaScript: Beginners Guide
Mico Gongob HackerNoon profile picture

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.


Originally published at https://micogongob.com/modern-javascript-function-defaults