How do I make my own JavaScript functions have required parameters?

Edit: If you were to use something like TypeScript you could get this kind of checking.

This is impossible to do in JavaScript without literally checking for the expected arguments (as VoronoiPotato already showed).

Every JavaScript function has access to an arguments variable. You can check to see if this has any arguments in it, and if they are of the types that you were expecting.

var foo = func(a, b) {

  if(arguments.length < 2 )
     Throw("error");

  if(typeof a !== '<expectedtype>' && typeof b !== '<expectedtype>')
     Throw("error");
};

If you are just concerned with the code completion bit then you can get that in the IntelliJ environment with the use of JSDoc comments. This does not affect your code, as others have pointed out you cannot specify to the JavaScript interpreter if a parameter is optional or not, but the editor will pick up the information from the comment and display it as you type. That way your own functions display similarly to the library functions.


function foo(value1, value2){
/**
* @param myParam1 [Required]
* @param myParam2
*/
  if(value1 == undefined){
    throw('Value1 is a required field for function foo');
  }
}

Using ES6 default function parameters, you can implement a Required FLAG, that will throw an error and stop execution, when a function with required parameters is called without providing them.

// set a getter to a custom global identifier (P_REQUIRED)
Object.defineProperty( window , 'P_REQUIRED'  , {
  get : ()=>{
    let err     = new Error('');
    let trace   = err.stack.split('\n');
    let msg     = '';
    for(let i=2;i<trace.length;i++)  msg+=trace[i]+'\n';
    throw 'Error : Missing required parameter\n' + msg; 
  },
  configurable : false
});


// declare a function with a mandatory parameter
function myFunc( myParam = P_REQUIRED ){
  /* some code here */
}

// call the function without the parameters
myFunc();
  
// Error is thrown!

Essentially, P_REQUIRED is assigned to the parameter by the interpreter, when no value has been specified in the function call. This triggers the getter handler, which simply prepares and throws a new Error.

It`s a clean and cross-browser solution, that will run in any modern environment (ES6 is required).

I actually packed it as a javascript module.
+info : https://github.com/colxi/P_REQUIRED