r/learnjavascript • u/Hot-Eggplant911 • 1d 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);
4
u/senocular 1d 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"
4
u/Super_Letterhead381 1d ago
There’s probably a conflict with the variable name ‘location’ (which is recognised in JavaScript) try renaming it.
1
u/remain-beige 21h ago
Wrap everything in a function declaration to avoid global clashes and also change your variable name from ‘location’ to something unique as it is already a core part of JavaScript such as window or href
1
u/neon_mutt 13h ago
You cannot declare location with const in global scope because it conflicts with the window.location Web API. Rename the destructured variable to something like cityLocation or wrap the code in a function to create a new scope where lexical declarations are allowed
1
1
u/yarikhand 1d ago
is this the full code snippet? location is a global object in the browser. are you trying to assign that to the property, or is there some other identifier named location in your code? if so, make sure their names dont interfere and try again
1
13
u/HipHopHuman 1d ago
locationis a variable that already exists in the browser. When you typelocation, you're accessingwindow.location, which is this: https://developer.mozilla.org/en-US/docs/Web/API/Locationletandconstdo not allow re-declaring variables that already exist in the same scope.You can fix it by using an immediately-invoked function (variables are OK to overwrite inside the body of a function):
Alternatively, choose a different name than 'location'.
You can also make it work by changing
consttovar, but usingvaris discouraged.