Search code examples
javascriptangulartypescript

<<closed>>This condition will always return 'false' since JavaScript compares objects by reference, not value, what does this mean in the Scenario?


in TS 4.9.3 and angular 15 application, i have a service function isEmpty() with following snippet of code.

    static isEmpty(value: any): boolean {
        if (value === null || value === undefined || value === {} || value === []) { 
            return true;
        }
    }

and it generates This condition will always return 'false' since JavaScript compares objects by reference, not value. issue for conditions value === {} and value === [].


Solution

  • As the error states, in JavaScript objects are compared by reference. So you cannot compare object values like {} === {}. Something like this will always return false because both {} have different memory addresses.

    In your case you compare an argument value to a newly created object ({}). The condition will always return false since there is no way for the objects to have the same reference. TypeScript detects this and warns you about this by showing an compiler error. Also the TypeScript control-flow analysis notices that the function never returns the annotated return type boolean resulting in another compiler error.

    This feature was added in TypeScript 4.8 (Errors When Comparing Object and Array Literals)

    [...] We believe that similar code in JavaScript is at best an early foot-gun for JavaScript developers, and at worst a bug in production code. That’s why TypeScript now disallows code like the following.