4
export class SearchResult {
    id: string;
    constructor(obj?: any) {
        this.id = obj && obj.id || null;
    }
}

What does obj && obj.id || null mean? I don't get this syntax.

4
  • It checks if object exists and id is present on that object or null. that seems to be some interesting javascript in that, there is a similar question that perhaps answers your question here Commented Mar 3, 2019 at 20:33
  • Right, so null seems to be the default value, but how does javascript knows what to return between obj && obj.id? it is because obj.id is a property? Commented Mar 3, 2019 at 20:41
  • @PeterNguyen Did my answer help? Commented Mar 5, 2019 at 22:01
  • 1
    @BenSmith yes thank you! Commented Mar 7, 2019 at 9:20

1 Answer 1

6

Whilst your code is using Typescript, this question actually concerns JavaScript.

In JavaScript:

true && expression

will cause the expression to be evalauted.

As for:

false && expression

this will evaluate to false causing the expression to not be evaulated.

Hence in your constructor, if obj is truthy (e.g. neither null or undefined) the expression will be evaluated, in this case accessing the obj.id and assigning its value to this.id. If obj is not truthy, then it will evaluate to false, and the null value will get assigned to this.id.

This technique is often used in React, see here for an example.

Sign up to request clarification or add additional context in comments.

2 Comments

WOW! Somehow, this has evaded me for years! I've always thought true && expression evaluated to true. I guess because usually when I use this concept, I'm trying to use the value as truthy and it works
@Scrimothy it's a really useful technique for writing succinct code :) I guess one will only consider it succinct though if they understand what's going on!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.