Seshan's Blog
keyboard_backspaceBack to PostsJS Tip: Object Initialization Shorthand!
July 26, 2019
Let’s say your writing some React code, and you end up doing something like this:
let a = 123;
let b = 456;
let c = 789;
this.setState({ a: a, b: b, c: c })
Having to write out variable names twice in your setState() statement seems a bit inefficient. Thankfully, there is a better way in ES2015:
let a = 123;
let b = 456;
let c = 789;
this.setState({ a, b, c })
That’s so much nicer! The object will be automatically initialized with the name of the variable as the property name. Awesome, isn’t it?
By the way, I hope you guys like this new segment I’m calling JS Tips. Anytime I find little useful JS tidbits I feel like sharing, I’ll create a new installment of JS Tips!
ID: 186