I have searched for "JavaScript return false not working" and similar strings, but what I find is mostly people who are not getting the expected behavior for JS that is embedded in HTML. This code is not part of a web page. I am doing a coding challenge that ought to be pretty simple, but I am experiencing strange behavior and would love input from someone who knows what is going on.
The challenge is to test if a string contains properly nested brackets. I thought to solve this with a stack and a simple object matching up closing and opening brackets. My code is as follows:
function validBraces(str) {
const openers = ['(', '{', '['];
const matches = { '(':')', '{':'}', '[':']' };
const stack = [];
str.split("").forEach((ch) => {
if (openers.indexOf(ch) > -1) {
stack.push(ch);
} else {
const currentBrace = stack.pop();
if (matches[currentBrace] !== ch) {
console.log("false!");
return false;
}
}
});
if (stack.length === 0) {
return true;
}
}
The strange thing is, when passed a string that is not made of properly nested brackets, and should therefore return false, this code will log "false!" but does not return false. It still returns 'true'. How is that even possible? What is going on? Does anyone know? I would really love to understand what is happening. Thanks!