CodexBloom - Programming Q&A Platform

JavaScript Function Returns Undefined When Trying to Access Nested Object Properties

👀 Views: 1779 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
javascript optional-chaining functions JavaScript

I've looked through the documentation and I'm still confused about I'm stuck on something that should probably be simple... I'm having trouble with a JavaScript function that isn't returning the expected value when trying to access properties of a nested object. Here's what I've got: ```javascript const user = { id: 1, profile: { name: 'Alice', address: { city: 'Wonderland', zip: '12345' } } }; function getUserCity(user) { return user.profile.address.city; } console.log(getUserCity(user)); // Should print 'Wonderland' ``` The function seems straightforward, but occasionally it returns `undefined`. After checking the console, I realized that the `profile` or `address` properties might not always exist. I tried adding checks like this: ```javascript function getUserCity(user) { if (user && user.profile && user.profile.address) { return user.profile.address.city; } return 'City not available'; } ``` This works, but I'm concerned about the readability and performance, especially since this function can be called frequently in a loop. I was considering using optional chaining (available in ES2020) to simplify the code: ```javascript function getUserCity(user) { return user?.profile?.address?.city || 'City not available'; } ``` Upon testing, this version returns 'City not available' when properties are missing, which is great, but I'm still unsure if using optional chaining impacts performance negatively in a high-frequency scenario. Is this approach best practice, or should I stick with the explicit checks? Also, are there any potential pitfalls with optional chaining that I should be aware of? Any insights would be greatly appreciated! This is my first time working with Javascript LTS. Any ideas what could be causing this? I'm using Javascript LTS in this project. I'd really appreciate any guidance on this.