๐Ÿ›  Accordion: Using useful JavaScript features

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

๐Ÿ›  Accordion: Using useful JavaScript features

You can apply 3 useful JavaScript features on the accordion:

  1. Early returns
  2. Ternary operators
  3. Template literals

Using early returns

When a user clicks inside .accordion-container, we checked whether .accordion__header is an ancestor of the event.target.

accordionContainer.addEventListener('click', event => {
  const accordionHeader = event.target.closest('.accordion__header')

  if (accordionHeader) {
    // Open and close accordion
  }
})

We can simplify this with an early return.

accordionContainer.addEventListener('click', event => {
  const accordionHeader = event.target.closest('.accordion__header')
  if (!accordionHeader) return

  // Open and close accordion
})

Using ternary operators

When we get the height of the accordion, we did this:

let height

if (accordion.classList.contains('is-open')) {
  height = 0
} else {
  height = accordionInner.getBoundingClientRect().height
}

We can rewrite this with a ternary operator.

const height = accordion.classList.contains('is-open')
  ? 0
  : accordionInner.getBoundingClientRect().height

Using template literals

When we set the height of an accordion, we had to write + px after height. We do this because JavaScript gives you a px value from getBoundingClientRect.

accordionContent.style.height = height + 'px'

We can simplify this a bit with template literals.

accordionContent.style.height = `${height}px`

Thatโ€™s it!