Node.js destructure undefined

fix undefined error

·

1 min read

To simplify our code, Node.js offer Destructure syntax to de-strcuture the objects with properities.

Meanwhile, ES6 offer Defautl Function Paramerters in case the parm not provided.

const greet = (user='Fabio') =>{
    console.log('Hello', user);
}

greet('Richard')    // Hello Ricahrd
greet()             // Hello Fabio

To deal with objectes, there might be a chance that the object is undefined. In such case, the de-structure will hit error.

const product = {
    price: 200.00,
    name: 'iPhone 13',
    category: 'mobile'
}

const hello = ({price, name}) => {
    console.log(name, price);
}

hello(product)
hello() //TypeError: Cannot destructure property `price` of 'undefined' or 'null'.

To prevent such error, we could make sure of Default Function Parameters to assign default value in case error. Take note on the syntax {price, name} = {} which assign empty object for the properties.

const hello = ({price, name} = {}) => {
    console.log(name, price);
}