Default values while Destructuring in JavaScript

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months

Just before showing the example, we will see how to do destructuring in basic examples

Destructuring Objects

// for simple object
const obj = {
  name: 'Param',
  city: 'Tallinn',
  age: 20,
  company: 'learnwithparam OU',
}

const { name, age, ...rest } = obj

console.log(name) // Param
console.log(age) // 20
console.log(rest) // { city: 'Tallinn', company: 'learnwithparam OU', }

Destructuring Arrays

const personArr = [
  {
    name: 'Param',
  },
  {
    name: 'Ahmed',
  },
  {
    name: 'Jesus',
  },
]

const [first, ...restOfArr] = personArr

console.log(first) // { name: 'Param' }
console.log(restOfArr) // [{ name: 'Ahmed' }, { name: 'Jesus' }]

Destructuring not defined variable

What will happen if we destructure an undefined key in the object. Example,

const firstObj = {
  name: 'Param',
  city: 'Tallinn',
  age: 20,
  company: 'learnwithparam OU',
}

const { firstName, city } = firstObj

console.log(firstName) // undefined
console.log(city) // Tallinn

Default value while destructuring

Now we can pass in default value while destructuring, it will take the default if it is undefined. Example,

const secondObj = {
  firstName: 'Param',
  country: 'Estonia',
}

const { lastName = 'Harrison', country } = secondObj

console.log(lastName) // Harrison
console.log(country) // Estonia

Here in this example, even though lastName is not defined in object, it takes the default value we assigned while destructuring.

This will be very useful when you want to have default values set in your application even if there is no value in the object.

Edge case while setting default value in destructuring

This has an edge case though, destructuring will work well with default value if the value is undefined. It won't work for other non true values, for example null, 0, false.

Let see it in example,

const edgeCase = {
  why: undefined,
  what: null,
  how: 0,
  where: false,
}

const {
  why = 'why',
  what = 'what',
  where = 'where',
  how = 'how',
  notFound = 'Not Found',
} = edgeCase

console.log(why) // why
console.log(what) // null
console.log(how) // 0
console.log(where) // false
console.log(notFound) // Not Found

Hope you enjoyed and learnt some tricks about destructuring in javascript šŸ˜Ž

Checkout the examples here,