Search This Blog

2026/08/10

Javascript : make function parameter required

 




function checkParam() {
   throw new Error('Parameter is required');
}

function myFunction(param=checkParam()) {
   console.log(param);
}


myFunction('Hello'); // Output: Hello
myFunction(); // Throws an error: Parameter is required

Output:
Hello
C:\Users\sangr\Practice\paramRequired.js:2
   throw new Error('Parameter is required');
   ^

Error: Parameter is required
    at checkParam (C:\Users\sangr\Practice\paramRequired.js:2:10)
    at myFunction (C:\Users\sangr\Practice\paramRequired.js:5:27)
    at Object.<anonymous> (C:\Users\sangr\Practice\paramRequired.js:11:1)
    at Module._compile (node:internal/modules/cjs/loader:1734:14)
    at Object..js (node:internal/modules/cjs/loader:1899:10)
    at Module.load (node:internal/modules/cjs/loader:1469:32)
    at Function._load (node:internal/modules/cjs/loader:1286:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:151:5)

Node.js v23.9.0


Explanation:
In this code, we define a function `checkParam()` that throws an error if it is called.
The `myFunction()` function takes a parameter `param`, which defaults to the result
of calling `checkParam()`. If `myFunction()` is called without an argument,
`checkParam()` is invoked, resulting in an error being thrown. If `myFunction()` is
called with an argument, it simply logs that argument to the console.

No comments:

Post a Comment