Option parameters as booleans

I’m currently working with Node and using a few npm modules. This is my first time really taking a bit of a deeper dive into working with them. I was reading the doc for postman API request method, but had no idea on how to implement the optional parameters. Then I realized that it can passed as an object with boolean value. In the docs I did not see anything that said it needs to be passed as an object with boolean value. Is it just assumed that npm module methods that have options parameters need to be passed with a boolean value? I find this a bit confusing that some docs are not clear on this so I’m assuming this is standard practice.

Anything can be a default argument. In ES6 there is a lesson on it: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions

Otherwise, when JavaScript doesn’t get an argument passed in, the argument is set to undefined. You can check for an undefined argument and set it to whatever you like.

Update: I did see in the docs that this method references the another method which must be set as true or false. I guess its more about becoming familiar with the specific module and how it works.

Optional arguments as the person above said, are set to undefined when you don’t pass them. The maintainer of the package can decide to use “default values” so that when you don’t pass the argument, a default value of their choice is set instead.

This is different but kinda the same when the maintainer chooses to use a “config object” instead by providing a set of default key-value pairs.

function foo(obligatory, optionalDefault = 0, optionalIgnored) {
  if (obligatory === undefined) {
    throw new Error("Obligatory argument not passed");
  }
  
  console.log(obligatory, optionalDefault, optionalIgnored);
}

foo('Example with variables');
// Example with variables, 0, undefined
function bar(config) {
  const defaults = {
    a: 5,
    b: 'B',
    c: true
  };
  config = { defaults, ...config };

  console.log(config);
}

bar({ c: false }); // Only c was rewritten
// { a: 5, b: 'B', c: false }
2 Likes

Thanks for explaining and helping me to further understand. I don’t like to use things unless I fully understand whats going on under the hood. I dug into the actual source code and indeed found it was being passed as some sort of object yet I’m not sure where to draw the line sometimes on how far I should dive into really understanding whats under the hood.