Seshan Ravikumar

aka. Seshpenguin


← Back

title: 'JS Tip: Object Initialization Shorthand!' author: Seshan Ravikumar type: post date: 2019-07-26T23:59:59+00:00 url: /2019/07/26/js-tip-object-initialization-shorthand/ classic-editor-remember:


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!