I am confused why this function would ever return true. If an item is added to the stack, then returning !stack.length would return false, right? I think I am missing something about how the stack works but I cannot seem to find the answer.
var isValid = function (s) {
const hash = {
'(': ')',
'{': '}',
'[': ']',
};
const stack = [];
for (const char of s) {
if (char in hash) stack.push(char);
else {
const top = stack.pop();
if (top === undefined || hash[top] !== char) {
return false;
}
}
}
return !stack.length;
};
That will happen when the length of the stack is equal to 0. Putting a ! in front of stack.length will evaluate NOT 0. The result of this is true.
Take a look at here. Or to be very specific:
If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false