Reputation: 3
I have one question. Help me, please.
I have code in my teaching proggram:
alert(user.address ? user.address.street ? user.address.street.name : null : null);
But I can't understand, why he used "null" two times at the end of the code?
I understand that if user.adress
- exist, then check whether user.address.street
exist, if user.address.street
- exist, then check whether user.address.street.name exist
, if not alert - null
.
But why did he write second null
?
Upvotes: 0
Views: 122
Reputation: 1
here user.address ? is condition sentence that have two operand. the first one is whole
user.address.street ? user.address.street.name : null
If the condition is true we'll go deeply to this sentence that is a condition sentence by own and have two operand again: first one is user.address.street.name
(if nested condition is true
) and the second one is null
(if the nested condition is false
).
the last null is the second operand of user.address ?
if it's false
.
Upvotes: 0
Reputation: 906
The ? operator is a shorthand for an if-else assignment.
alert(user.address ? user.address.street ? user.address.street.name : null : null);
Is the short form for:
let res;
if (user.address) {
if (user.address.street) {
res = user.address.street.name;
} else {
res = null;
}
} else {
res = null;
}
alert(res);
In javascript there is also the 'optional chaining operator' which is probably what you want:
alert(user?.address?.name);
Which only access the objects properties if they are not null, otherwise returns null.
Upvotes: 3