Created
March 27, 2018 10:33
-
-
Save azder/9f4e46ff0c669adeab5bc44713638d7f to your computer and use it in GitHub Desktop.
Optional and mandatory values in JS functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mandatory = ( | |
message => { | |
throw new Error(message); | |
} | |
); | |
function f({ | |
optional = 'not provided', | |
required = mandatory('the parameter "required" must not be null or undefined'), | |
} = {}) { | |
return { | |
'optional is': optional, | |
'required is': required, | |
}; | |
} | |
console.log(f({required: 'asdf'})); //=> { 'optional is': 'not provided', 'required is': 'asdf' } | |
const g = ( | |
({ | |
optional = 'not provided', | |
required = mandatory('the parameter "required" must not be null or undefined'), | |
} = {}) => ({ | |
'optional is': optional, | |
'required is': required, | |
}) | |
) | |
console.log(g()); //=> Error: the parameter "required" must not be null or undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment