18

I'm using destructuring to declare some variables like this:

const { a, b, c } = require('./something'),
    { e = 'default', f = 'default'} = c;

Is there a way to make this into single line? I've tried something like :

const { a, b, c = { e = 'default', f = 'default'} } = require('./something');

But it gives me an error:

SyntaxError: Invalid shorthand property initializer

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38

3 Answers3

24

The above code will not work if the object does not have c in it

const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
This will print out an error. For completion, you could as a simple "={}" as default

const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
Evilsanta
  • 1,032
  • 11
  • 18
  • In above example what if I want to take c[0]? If c[0] is not there then it should return blank object. const obj = { a: 'a', b: {}, c: [] } – Nikhil Mahirrao Nov 01 '19 at 12:00
17

Just replace = with ::

const {a, b, c: {e = 'default', f = 'default'}} = require('./something')

Demo:

const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2, c: {e: 3}}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

It prints:

a: 1, b: 2, e: 3, f: default
Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • 1
    this doesn't work if you're destructuring using `const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2}`, which raises a TypeError. – lochiwei Nov 03 '22 at 15:02
4

This example will help you to understand the destructing of array and object with fallback values.

You can use the = symbol for adding fallback or default value while destructing.

const person = {
  firstName: 'Nikhil',
  address: {
    city: 'Dhule',
    state: 'MH'
  },
  /*children: [
    { 
      name: 'Ninu',
      age: 3
    } 
  ]*/
}

const { 
  firstName, 
  address: {
    city,
    state
  },
  children: { 
    0: { 
      name='Oshin' // Fallback for name is string i.e 'Oshin'
    }={} // Fallback for 1st index value of array is blank object
  }=[] // Fallback for children is blank array
} = person;
  
console.log(`${firstName} is from ${city} and his first child name is ${name}`);
Nikhil Mahirrao
  • 3,547
  • 1
  • 25
  • 20