Let's assume that you have the following lines:
javascriptlet erik setTimeout(() => erik = { city: 'Bangkok', age: 31 }, 5000)
What happens if you try to destructure before the assignment is done?
javascriptlet { city, age } = erik // Uncaught TypeError: Cannot destructure property 'city' of 'erik' as it is undefined.
To solve it:
javascriptlet { city, age } = erik || {}
Now:
javascript// If the destructure is done before the assignment is done console.log(city) // undefined console.log(age) // undefined // If it's done afterwards console.log(city) // Bangkok console.log(age) // 31
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.