Required Parameters for Functions in JavaScript
Fri Apr 24 2020 11:32:35 GMT+0000 (UTC)
Saved by
@Dimples
#javascript
#javascript
#functions
#parameters
const isRequired = () => { throw new Error('param is required'); };
const hello = (name = isRequired()) => { console.log(`hello ${name}`) };
// These will throw errors
hello();
hello(undefined);
// These will not
hello(null);
hello('David');
The idea here is that it uses default parameters, like how the b parameter here has a default if you don’t send it anything:
function multiply(a, b = 1) {
return a * b;
}
content_copyCOPY
Ooo this is clever!
So above, if you don’t provide a name, it’ll use the default instead, which is that function that throws an error.
https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/
Comments
@juliyvchirkov - Sat Jan 08 2022 22:39:16 GMT+0000 (UTC)Brilliant!