A short post on Required parameters in JavaScript

A short post on Required parameters in JavaScript

·

2 min read

From MDN docs a parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions.

In this brief post, we'll see about using default parameter and parameter validation in JavaScript.

Parameter Validation

There are cases in which we might want some parameters to be passed as mandatory in order for a function to work. We usually use if condition to validate them.

function powerOf (a, b) {
    if (!a || !b) {
        throw new Error('Required parameter missing!'); 
    }
    return a ** b; 
}

If the condition is ok, but we can also handle this using the ES6 default parameters as well.

Using default parameter

If no value or undefined is passed then default values are initialized to the function parameter. We can use this to our advantage.

// global function
function require() {
    throw new Error('Required parameter is missing');
}; 

function powerOf (a = required(), b = required()) {
    return a ** b; 
}

powerOf(2, 2); // ouput 4
powerOf(2);    // throws error
powerOf();    // throws error

Removal.AI - [SPONSOR]

Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.

  • ✅ Drag & Drop Multiple Images
  • ✅ Optimize Product Images
  • ✅ Select Your Background
  • ✅ Set Your Output Size
  • ✅ Exceptional Results

Removal AI

Visit -> Removal AI

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!