简体   繁体   中英

Scroll Event Listener: Empty While loop, how does it work and why?

This question is in reference to this post .

In summary, the requirement is to have the links in the navigation to change status based on the current scroll position, I was able to get the code presented here to work, but one line which I don't understand why it's done this way is

while(--index && window.scrollY + 50 < sections[index].offsetTop) {}

I would've commented on the original answer post, but apparently, my reputation is not enough yet.

This is the whole JavaScript code

const links = document.querySelectorAll('.links');
const sections = document.querySelectorAll('section');

function changeLinkState() {
  let index = sections.length;

  while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
  
  links.forEach((link) => link.classList.remove('active'));
  links[index].classList.add('active');
}

changeLinkState();
window.addEventListener('scroll', changeLinkState);

Why is the while loop needed and since it's empty wouldn't it do anything? I tried removing the while loop and it ended up breaking the code.

while(--index && window.scrollY + 50 < sections[index].offsetTop) {}

This decrements the index with each iteration. The loop stops when window.scrollY + 50 < sections[index].offsetTop is false, and the index remains to the value of the last 'passed' check.

It is later used to update links[index].classList.add('active');

It could have been written like this also:

while (index >= 0 && window.scrollY + 50 < sections[index].offsetTop) {
    index--
}

It is required to check if index has a adequate value (aka not -1 or lower), or it will error when it reached -1, as sections[-1].something does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM