Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading