Search code examples
javascriptnull

Is it necessary to use null two times at the end of the code?


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?


Solution

  • 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.