Skip to content Skip to sidebar Skip to footer

Es6 Object Destructuring Mandatory Parameters

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

Solution 1:

You could assign the same variable, it throws an error Use before declaration, if not given.

functionname({ id = null, name = 'user', password = password }) {
    console.log(password);
}
name({});

If set, then it works without error.

functionname({ id = null, name = 'user', password = password }) {
    console.log(password);
}
name({ password: 'foo' });

Solution 2:

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:functionthrowRequired(name) {
  thrownewError(`'${name}' is required`);
}

functionname({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.

Solution 3:

You didn't make it required, you simply didn't provide a default value.

functionname({id = null, name = 'user', password}) {
     if (password == undefined) {
        thrownewError('password is required');
    }

The reason it threw an error the first time is because it tried to destructure undefined, which is impossible.

Solution 4:

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:

functionname({
  id = null, 
  name = 'user',
  password = (() => { thrownewError('password not defined'); })()
}) { 
  console.log(id, name, password);
}
  
name({ id: 1, name: 'the name', password: 'the password' }); // worksname({}); // throws an error

Post a Comment for "Es6 Object Destructuring Mandatory Parameters"