Reputation: 12449
Here is the function, password
is mandatory but other id
and name
have default values:
function name({id = null, name = 'user', password}) { }
Results:
name(); //throws error as expected
name({}); //passes 'password' as 'undefined' - should've thrown error
How can I make this function throw an error if password
is not provided using ES6 functionality?
Upvotes: 1
Views: 817
Reputation: 192006
Note: This is an ugly hack using the default parameters, and I prefer @Scimonster's answer.
You can actually run a function, and even an IIFE as a default param. The IIFE can throw an error:
function name({
id = null,
name = 'user',
password = (() => { throw new Error('password not defined'); })()
}) {
console.log(id, name, password);
}
name({ id: 1, name: 'the name', password: 'the password' }); // works
name({}); // throws an error
Upvotes: 2
Reputation: 1074555
Scimonster's answer is spot-on about what the probelm is.
If you like, you can handle it a bit more declaratively by using a utility function to throw an Error
in the function parameter list:
// Utility function:
function throwRequired(name) {
throw new Error(`'${name}' is required`);
}
function name({id = null, name = 'user', password = throwRequired("password")}) {
console.log("All is good, password is: " + password);
}
try {
name(); //throws error as expected
} catch (e) {
console.log("Got error from name():", e.message);
}
try {
name({}); //throws error as expected
} catch (e) {
console.log("Got error from name({}):", e.message);
}
name({password: "foo"}); // works
That works because the initializer on a default parameter is only evaluated if it's required to fill in the default.
Upvotes: 2
Reputation: 386654
You could assign the same variable, it throws an error Use before declaration
, if not given.
function name({ id = null, name = 'user', password = password }) {
console.log(password);
}
name({});
If set, then it works without error.
function name({ id = null, name = 'user', password = password }) {
console.log(password);
}
name({ password: 'foo' });
Upvotes: 4
Reputation: 33409
You didn't make it required, you simply didn't provide a default value.
function name({id = null, name = 'user', password}) {
if (password == undefined) {
throw new Error('password is required');
}
The reason it threw an error the first time is because it tried to destructure undefined
, which is impossible.
Upvotes: 2