This page looks best with JavaScript enabled

Assigning default values while object destructuring

 ·   ·  ☕ 1 min read

Easily assign default values while destructuring objects.

Consider below code-

1
2
3
4
const obj = { x: 9, y: 1 };
const { x, y } = obj;
console.log(x, y);
// 9 1

A typical destructuring of objects, this code assigns x and y variables to the x/y props of object obj.

This is a-ok, but what if you want to specify defaults in case any of the props are not present? Such defaults help avoid unexpected errors during further processing.

Consider below code -

1
2
3
4
const obj = { x: 9 };
const { x, y, z = 1 } = obj;
console.log(x, y, (z = 1));
// 9 undefined 1

What’s happening here -

  • Javascript tries to assign x, y, z variables to props in object.
  • Only x is found in object and the value is promptly updated to variable x
  • z is not defined and is assigned the default value 1
  • y stays undefined since there is no value present in the object and no default value is specified
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things