-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
28 lines (22 loc) · 728 Bytes
/
script.js
File metadata and controls
28 lines (22 loc) · 728 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const user = {
id: 1,
name: "John",
age: 25,
email: "jhon@gmail.com",
phone: "123456789",
website: "www.john.com",
};
console.log(user.name); // John
console.log(user.address); // undefined
console.log(user.address.city); // Uncaught TypeError: Cannot read property 'city' of undefined
// Solution 1 - Using if statement
if (user.address) {
console.log(user.address.city);
} else {
console.log("Address is not available");
}
// Solution 2 - Using ternary operator
// console.log(user.address ? user.address.city : "Address is not available");
console.log(user.address && user.address.city);
// Solution 3 - Using Optional Chaining
console.log(user.address?.city);