function - Why is JavaScript code executed while condition is false? (Eloquent JavaScript - Deep comparison) -


question (eloquent js 2nd ed, chapter 4, exercise 4):

write function, deepequal, takes 2 values , returns true if same value or objects same properties values equal when compared recursive call deepequal.

test cases:

var obj = {here: {is: "an"}, object: 2}; var obj1 = {here: {is: "an"}, object: 2}; console.log(deepequal(obj,obj1)); 

code:

var deepequal = function (x, y) {     if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {         if (object.keys(x).length != object.keys(y).length)           return false;          (var prop in x) {           if (y.hasownproperty(prop)){               if (! deepequal(x[prop], y[prop])) //should not enter!!                 return false;                 alert('test');           }else return false; // section do?         }         return true;     }     else if (x !== y)         return false;     else         return true; }; 

originaly fulfilled paul roub

main question: added alert block of code after if (! deepequal(x[prop], y[prop])) statement kind of debugging, , have no idea why code inside still executed while statement supposed return true , ! turns false..?
in addition: }else return false; for? (same statement) function seems work fine without section..

you added alert() in such way runs when if test fails, because didn't add { } match intention indicated indentation. if if test succeeds, following return statement exit function , alert() won't happen.

any code involves if or else if block returns nevertheless followed else clause code smell. either else or return redundant; it's matter of style way go.

that code flawed in tests number of properties object.keys() — implicitly looks @ "own" properties — uses for ... in loop through x without .hasownproperty() check. (whether inherited properties should affect concept of "equality" subjective, should symmetric @ least.)

oh, , first else return false clause after check see if y has 1 of properties in x quick exit. if y doesn't have property name that's in x, can't equal.

finally note sort of "deep" equality tester intends generic needs deal object graph cycles , other weirder things. (what of in object graph of x refers part of y, , vice versa?) deep object comparison not trivial thing.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -