Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!