🛠 Carousel: 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!

🛠 Carousel: Useful JavaScript features

We can use 4 of 11 features we learned for the carousel. They are:

  1. Early returns
  2. Template literals
  3. Rest and Spread operators
  4. Useful array methods

Using array spread

You can replace Array.from with the spread operator if you wish to:

// Change these
const slides = Array.from(carousel.querySelectorAll('.carousel__slide'))
const dots = Array.from(carousel.querySelectorAll('.carousel__dot'))
// To these
const slides = [...carousel.querySelectorAll('.carousel__slide')]
const dots = [...carousel.querySelectorAll('.carousel__dot')]

Using template literals

We can use template literals to move each slide.

// Change this
contents.style.transform = 'translateX(-' + destination + ')'
// To this
contents.style.transform = `translateX(-${destination})`

Early returns

We can use early returns in dot container’s event handler.

// Change this
dotsContainer.addEventListener('click', event => {
  const dot = event.target.closest('button')
  if (dot) {
    // Stuff here
  }
})
// To this
dotsContainer.addEventListener('click', event => {
  const dot = event.target.closest('button')
  if (!dot) return

  // Stuff here
})

JavaScript array features

When we searched for targetIndex in dot container’s event handler, we used a for loop. We can replace this with findIndex.

let clickedDotIndex

for (let index = 0; index < dots.length; index++) {
  if (dots[index] === dot) {
    clickedDotIndex = index
  }
}
const clickedDotIndex = dots.findIndex(d => d === dot)

And we’re done improving the carousel.