Skip to content

JavaScript named parameters | Example code

  • by

JavaScript doesn’t have a named parameters concept. But you can do something similar using object literals and restructuring.

fun({...})

In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:

JavaScript named parameters

A simple example is avoiding errors when calling the function without any arguments by assigning the object to the empty object, {}, even if you have default values set up.

<!DOCTYPE html>
<html>
<body>
  <script>

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

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


    console.log(example({ arg2: 4, arg1: 2 })); 
    console.log(example());
    
    problem(); //TypeError: Cannot read property 'failure' of undefined
  </script>

</body>
</html> 

Output:

JavaScript named parameters

Another example:

function exampleFunction(options) {
  // Default values
  const {
    param1 = 'default1',
    param2 = 'default2',
    param3 = 'default3'
  } = options;

  // Rest of the function using param1, param2, and param3
  console.log(param1, param2, param3);
}

// Calling the function with named parameters
exampleFunction({
  param1: 'value1',
  param3: 'value3'
});

Do comment if you have any doubts or suggestions on this JS parameters topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading