Thursday, April 25, 2019

javascript destructuring in function parameters

Reminder that Javascript destructuring is more powerful that it looks like

Sample

const theKey = 'key';

function f(
 {
  a: {
   b,
   // 'theDefaultValue'  is the default value in case theKey value is not 
   // defined in the object passed to the function
   [theKey] : theKeyValue = 'theDefaultValue' 
  }
 }
 ) {
  console.log(`b:${b}`);
  console.log(`theKeyValue:${theKeyValue}`);
}

f( 
 { a: {
   b:1, 
   'key': 'myValue'
  }
 }
);

f( 
 { a: {
   b:1 
  }
 }
);

Output

b:1
theKeyValue:myValue
b:1
theKeyValue:theDefaultValue

No comments:

Post a Comment