Search⌘ K

Solution Review: Destructure Undefined

Explore how to safely destructure objects in JavaScript when properties may be undefined. Understand three solutions using spread syntax, default assignments, and short-circuit evaluation to avoid errors and assign fallback values. This lesson helps you confidently manage object destructuring in real-world scenarios.

We'll cover the following...

The challenge in the previous lesson requires you to fix the following code using your understanding of object destructuring.

Node.js
function pointValues(point){
const {name:n,age:a} = point
console.log(n)
console.log(a)
}
var point = {name:"jerry", age: 2}
pointValues(point)
point = undefined
pointValues(point)

Solution 1 #

Node.js
function pointValues(point){
const {name:n,age:a} = {...point}
console.log(n)
console.log(a)
}
pointValues({name:"jerry", age:2})
pointValues(undefined)

Explanation #

The original code displays the name and age values of point if it is defined as an object; however, it gives an error if it is undefined. The ...