I have this piece of code (taken from this question):
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err)
return done(err);
var pending = list.length;
if (!pending)
return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending)
done(null, results);
});
} else {
results.push(file);
if (!--pending)
done(null, results);
}
});
});
});
};
I'm trying to follow it, and I think I understand everything except for near the end where it says !--pending
. In this context, what does that command do?
Edit: I appreciate all the further comments, but the question has been answered many times. Thanks anyway!
It's the not operator followed by the in-place pre-decrementer.
So if
pending
was an integer with a value of 1:That's not a special operator, it's 2 standard operators one after the other:
--
)!
)This causes
pending
to be decremented and then tested to see if it's zero.!
inverts a value, and gives you the opposite boolean:--[value]
subtracts one (1) from a number, and then returns that number to be worked with:So,
!--pending
subtracts one from pending, and then returns the opposite of its truthy/falsy value (whether or not it's0
).And yes, follow the ProTip. This may be a common idiom in other programming languages, but for most declarative JavaScript programming this looks quite alien.
It's a shorthand.
!
is "not".--
decrements a value.So
!--
checks if the value obtained from negating the result of decrementing a value is false.Try this:
The first is false, since the value of x is 1, the second is true, since the value of x is 0.
Side note:
!x--
would check if x is false first, and then decrement it.means
means
It merely decreases
pending
by one and obtains its logical complement (negation). The logical complement of any number different than 0 isfalse
, for 0 it istrue
.