Home > Mobile >  Identifier has been declared
Identifier has been declared

Time:09-24

since I am a beginner can't know what is happening there. could you help/explain to me what is happening?

It works with all the properties except the "location", it says:

property has been declared

'use strict';

const restaurant = {
  name: 'Classico Italiano',
  location: 'Via Angelo Tavanti 23, Firence, Italy',
  categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
  starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
  mainMenu: ['Pizza', 'Pasta', 'Risotto'],
  hello_kitty: function (two, three) {
    return [this.starterMenu[two], this.mainMenu[three]];
  },
};


const {location} = restaurant;
console.log(location);

CodePudding user response:

If you are using this code in the browser's console it is natural to get this error as location is a reserved name for the Location Object, an object that contains information about the current page URL.

See : enter image description here

CodePudding user response:

As your console tells: can't assign the location property into a new variable because it has been declared before.

this happened because your Javascript run in a environment (browser) and this environment has some variables and methods on it.

you can see this via:

console.log(window)

the result would be:

Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}

as you see, location is a predefined property that exists in your window object, so declaring new location property in the global scope was the cause of the issue.

if you are familiar with the scopes in Javascript, you can simply wrap your code snippet into a function to make it work properly:

'use strict';

function logLocation(){
   const restaurant = {
      name: 'Classico Italiano',
      location: 'Via Angelo Tavanti 23, Firence, Italy',
      categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
      starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
      mainMenu: ['Pizza', 'Pasta', 'Risotto'],
      hello_kitty: function (two, three) {
        return [this.starterMenu[two], this.mainMenu[three]];
      },
  };


  const {location} = restaurant;
  console.log(location);
}

logLocation()

  • Related