Uncaught SyntaxError: Identifier 'carts' has already been declared

Hey Guys!

I am very new to the world of web development.
I am creating a website for a friends new business, so am attempting to first create the shopping cart (I know... stuck on the first big hurdle haha). It was all going so well following this guys tutorial, every letter/syntax exactly the same, proofed about 50 times.

It's strange because the error started happening line 1 in my code (see below) around 75% of my way through the project (this part of it anyway), so when I got fed up I made a test copy of my documents and gradually took EVERYthing out to see if I could narrow it down to a typo... I even did this on html page too as I did some research and saw that one of the causes was a missing div tag. but I ended up with a pristine html doc and just the one line of JS code!! \/ \/ \/

This is the code on line 1 (the only code in the end still returning error!) See error in subject above.

**let carts = document.querySelectorAll('.add-cart');**

Now im a bit stuck when I am trying to ask for help here too(I imagine because im so new to all this hahaha), would you guys want to see all HTML and the entire Javascript docs? or can you work it out with what I said above :slight_smile:

As im so new, please 'spell it out to me' :) if you can!

So much appreciation goes to anyone that tries to help, this is driving me mad!

EDIT - Here you go!

Let me know if it would help to upload the whole project.

Thanks guys

I think you’re going to have to create a repo of the project so we can take a look.

maybe you’ve declared carts in another snippet of javascript…
Can you please provide code of page as mentioned by @kevinSmith

@mukeshgurpude @kevinSmith Please see edit in post

Right, but we’d need to see the whole app to try and find where the name collision is.

Two potential fixes:

1- Temporarily change let carts = ... to var carts = ... to see if that fixes things.

There’s a possibility your JS is getting rerun, and lets cannot be redeclared, but vars can.

2- Keep the let but change carts to something else like carts123, and update the references accordingly. This will tell you if there is another carts being declared in some other JS file you aren’t aware of.


And if you can get Eric’s second option work, I would printout what carts is just to see what it is. I suspect that it is being used in some other file or even in a library that you are importing.

1 Like

I would also suggest you wrap your code in a DOMContentLoaded to make sure the DOM is ready before you query it. It will also scope the variables.

Oh my! This seems to have done the trick!!

Thanks a lot buddy :slight_smile: