Search code examples
javascripttypescriptconditional-operator

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.


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.