Reputation: 223
I'm teaching myself JavaScript, and I'm stuck on the following problem from Eloquent JavaScript:
Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to deepEqual. To find out whether to compare two things by identity (use the === operator for that) or by looking at their properties, you can use the typeof operator. If it produces "object" for both values, you should do a deep comparison. But you have to take one silly exception into account: by a historical accident, typeof null also produces "object".
My question:
Why does console.log(deepEqual(obj, {here: {is: "an"}, object: 2}))
come out as false when a[key]
is { is: 'an' }
and b[key]
is { is: 'an' }
but true when that code is substituted with !deepEqual(a[key], b[key])
?
The code:
function deepEqual(a, b){
if (a === b) {
return true;
}
else if (typeof a== typeof b && !(a===null ||b===null)){
for(var key in b){
for(key in a){
if(! (key in a)){
return false;
}
else if (a[key] !== b[key]){
return false;
}
else
return true;
}
}
}
else
return false;
}
var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
Upvotes: 0
Views: 1466
Reputation: 245419
Because a[key]
and b[key]
are both Objects, you need to use deepEquals
on them as well.
Currently, you're not calling deepEquals
recursively, so there's no way that will happen.
Upvotes: 1