Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
How pop() work inside this if condition statement

In the code below

function validBraces(braces) {
  var matches = { '(': ')', '{': '}', '[': ']' };
  var stack = [];
  var currentChar;

  for (var i = 0; i < braces.length; i++) {
    currentChar = braces[i];
    if (matches[currentChar]) {
      stack.push(currentChar);
    } else {
      if (currentChar !== matches[stack.pop()]) {
        return false;
      }
    }
  }
  return stack.length === 0;
}

To my understanding, this code

currentChar !== matches[stack.pop()]

check that current char is the necessary opening braces of last element in the stack array and if it is correct it pop the last element in stack array. but in the syntax, there is no condition if it matches, like this

if(currentChar == matches[stack.pop()]
{stack.pop()} 

So, is stack.pop() working inside the if condition statement despite there is no true condition for it. How exactly is it working here?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The expression is evaluated from inside out.

pop removes the last element from the array and returns the removed value. And this character (because stack contains only characters) is used to access the respective property in the matches object.

You can rewrite the code as follows:

if (currentChar !== matches[stack.pop()]) {
  return false;
}

is equivalent to

let stackElement = stack.pop();
let match = matches[stackElement];
if (currentChar !== match) {
  return false;
}

EDIT regarding your comment

No returning true from this position in the code doesn't have anything to do with the "characteristic" of pop (whatever you mean by that).

The whole function is a check for balanced braces. And that specific part of the code checks, whether the current char is the matching equivalent of the current element on the stack. If that's not the case, the braces are not correctly matched, thus you can immediately return false. But you cannot return true at this position, because to be able to determine, that the braces are correctly matched, you have to examine the whole input string. Thus, the last line of the function

return stack.length === 0;

where you check, after the whole string as been handled, if all braces have been correctly matched. If stack.length === 0 gives false, there are still unmatched braces on the stack, thus the result of the function is false. If stack.length === 0 gives true, there is no unmatched brace left, thus the result of the function is true

about 4 years ago · Juan Pablo Isaza Relatório

0

stack.pop() is executed before evaluation of the expression. It would be identical to the following code:

// ...

const lastEncounteredOpeningBracket = stack.pop();
const requiredClosingBracket = matches[lastEncounteredOpeningBracket]

if (currentChar !== requiredClosingBracket ) {
  return false;
}

// ...
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda