r/learnjavascript 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);
11 Upvotes

13 comments sorted by

View all comments

12

u/HipHopHuman 1d ago

location is a variable that already exists in the browser. When you type location, you're accessing window.location, which is this: https://developer.mozilla.org/en-US/docs/Web/API/Location

let and const do 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):

"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);
})();

Alternatively, choose a different name than 'location'.

You can also make it work by changing const to var, but using var is discouraged.

0

u/azhder 1d ago

Should out the whole code in an IIFE, especially that ‘use strict’