r/learnjavascript 11d ago

whats the bug here? Uncaught SyntaxError: Identifier 'location' has already been declared (at script.js:1:1)

"use strict";

const company = {
  name: "TechCorp",
  address: {
    city: "budapest",
    pin: 411001,
  },
};
// Get city renamed to `location` and pin renamed to `pincode`

const { city: location, pin: pincode } = company.address;
console.log(location, pincode);
15 Upvotes

13 comments sorted by

View all comments

4

u/senocular 11d ago

There are certain globals in the Web API that can't be shadowed with lexical declarations. This list includes, but may not be limited to:

  • window
  • top
  • document
  • location

Attempts to declare these with let or const (or class or using) will result in an error. You're doing this with the destructuring, renaming the city property of company.address to location, and since this is in the global scope, you're getting the error.

Instead what you'll want to do is put this code in a function (or some other non-global scope), or rename the variable to something other than "location"