How to Use Named Parameters in JavaScript

Apr 16, 2021

JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {}, even if you have default values set up.

function example({ arg1 = 1, arg2 = 2, arg3 = 3 } = {}) {
  return { arg1, arg2, arg3 };
}

function problem({failure = true}) {
  return failure;
}

problem(); //TypeError: Cannot read property 'failure' of undefined

example({ arg2: 4, arg1: 2 }); // { arg1: 2, arg2: 4, arg3: 3 }

example(); // { arg1: 1, arg2: 2, arg3: 3 }

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials