Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
using break in ternary/operator expression giving "Expected Output"

I created a function for getting last child element using TypeScript.

If I use normal if/else typescript not raising any error.

function lastChildElement(element: HTMLElement) {
  let lastChild = element.lastChild

  while (lastChild && lastChild.nodeType != 1) {
    if (lastChild.previousSibling) {
      lastChild = lastChild.previousSibling
    } else {
      break
    }
  }

  return lastChild
}

but when using ternary/conditional expression

function lastChildElement(element: HTMLElement) {
  let lastChild = element.lastChild

  while (lastChild && lastChild.nodeType != 1) {
    lastChild.previousSibling ? lastChild = lastChild.previousSibling : break
  }

  return lastChild
}

typescript underlining break keyword and raising Expression expected.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The conditional operator evaluates to a value. That is, if you have

someExpression ? someOtherExpression : yetAnotherExpression

The entire thing will then evaluate to either someOtherExpression or yetAnotherExpression.

But break is not a value - it's not an expression - it's a statement that can't be evaluated as anything, so it's not permitted in the context where an expression is expected.

For similar reasons, you can't do:

while (someCondition) {
  const something = break;
  // ...

which just doesn't make sense.

Use if/else, so that you can break as a standalone statement if needed.

That said, a better alternative to iterating through all children is to select the last element child directly.

const lastChildElement = (element: HTMLElement) => element.lastElementChild;

No loops needed.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda