The console error – "Uncaught SyntaxError: redeclaration of let sectionSelector"
The code –
<script type="text/javascript">
const sectionSelector = '#shopify-section-{{ section.id }}';
let collectionSelectors = document.querySelectorAll(`${sectionSelector} .recommendations__collection-selector`);
for (let collectionSelector of collectionSelectors) {
let blockId = collectionSelector.dataset.blockId;
let collectionCarousel = document.querySelector(`${sectionSelector} .recommendations__collection[data-block-id="${blockId}"]`);
let otherCarousels = document.querySelectorAll(`${sectionSelector} .recommendations__collection:not([data-block-id="${blockId}"])`);
collectionSelector.addEventListener('click', () => {
for (let otherCarousel of otherCarousels) {
otherCarousel.classList.remove('active');
}
for (let collectionSelector of collectionSelectors) {
collectionSelector.classList.remove('active');
}
collectionSelector.classList.add('active');
collectionCarousel.classList.add('active');
window.dispatchEvent(new Event('resize'));
})
}
</script>
I first changed let sectionSelector
to const
, that changes the error to collectionSelectors. This is the only reference to sectionSelector I have on the site, the error persists even if I have a single line –
let sectionSelector = '#shopify-section-{{ section.id }}';
So my question is how is the variable being reassigned if there aren’t any new declarations. I’m starting to think it has something to do with the for loops using for…of?
2
Answers
An iteration variable
collectionSelector
is declared in the first loop, and then in the loop inside the event listener you declare the iterator the same way, bbut the second loop shares the scope of the first one, just change the name in the second loopYou are declaring
collectionSelector
variable two times Infor loop
I the first
for loop
scope there is already a variable calledcollectionSelector
, that’s why there is an error. Change that to some another variable name, error should be fixed.