Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):
Write a function, deepEqual, that takes two values and returns true only if th
You can use a variable outside the for loop to keep track of the comparison:
var allPropertiesEqual = true;
for (var prop in x) {
if (y.hasOwnProperty(prop)) {
allPropertiesEqual = deepEqual(x[prop], y[prop]) && allPropertiesEqual;
} else {
allPropertiesEqual = false;
}
}
return allPropertiesEqual;
The previous example is not optimized on purpose. Because you're comparing objects, you know that you can return false as soon as you find an inequality, and you can keep looping while all the previous checked properties are equal:
for (var prop in x) {
if (y.hasOwnProperty(prop)) {
if (! deepEqual(x[prop], y[prop]) )
return false; //first inequality found, return false
} else {
return false; //different properties, so inequality, so return false
}
}
return true;