Javascript ES6 Destructuring - identifier "location" already declared

I have a simple array of objects and you want to get the location attribute of the first element:

const companies = [
  { name: 'Google', location: 'Mountain View' },
  { name: 'Facebook', location: 'Menlo Park' },
  { name: 'Uber', location: 'San Francisco' }
];

const [{ location }] = companies; 
// expected: Mountain View but got Uncaught SyntaxError: Identifier 
//'location' has already been declared at <anonymous>:1:1
Run code

What am I missing?

+4
source share
4 answers

You cannot override a global variable locationas a constant. If you used let [{location}] = companies, you would not have an error, but you would have the wrong behavior, as it would try to assign a value window.locationand redirect the page.

Possible solutions:

  • Change the variable name (along with the property name)
  • Wrap your code in a block (in this case IIFE is not required, since we use ES6)
  • , .

const companies = [
  {name: 'Google',loc: 'Mountain View'},
  {name: 'Facebook', loc: 'Menlo Park'},
  {name: 'Uber', loc: 'San Francisco'}
];

const [{loc}] = companies;
console.log(loc);

// Block scope
{
  const companies = [
    {name: 'Google', location: 'Mountain View'},
    {name: 'Facebook', location: 'Menlo Park'},
    {name: 'Uber', location: 'San Francisco'}
  ];
  const [{location}] = companies;
  console.log(location);
}

// Variable name doesn't have to be the same as property
const [{ location: loca }] = [{location: 'Mountain View'}]
console.log(loca);
+9

, .

IIFE (Expression Exposed Function Expression), .

, , , , /.

var const, window.location, 404, URL .

IIFE, , .

IIFE ( ):

(() => { // ES2015 IIFE
    "use strict";
    
    const companies = [
      { name: 'Google', location: 'Mountain View' },
      { name: 'Facebook', location: 'Menlo Park' },
      { name: 'Uber', location: 'San Francisco' }
    ];
    
    const [{ location }] = companies;
    console.log(location);
})();

:

{ // ES2015 block
    "use strict";
    
    const companies = [
      { name: 'Google', location: 'Mountain View' },
      { name: 'Facebook', location: 'Menlo Park' },
      { name: 'Uber', location: 'San Francisco' }
    ];
    
    const [{ location }] = companies; 
    console.log(location);
};

ES2015 , , let const ( var)

, , ES2015, Babel JS .

+4

, location , window.location.

, , . ES6, IIFE ES5:

{
  ...
  const [{ location }] = companies; 
}

Typical use of ES6 is a modular environment. Given that the current scope is a CommonJS or ES6 module, the problem will never appear.

0
source
const companies = [
  { name: 'Google', location: 'Mountain View' },
  { name: 'Facebook', location: 'Menlo Park' },
  { name: 'Uber', location: 'San Francisco' }
];

console.log(companies[0].location);
-3
source

Source: https://habr.com/ru/post/1666611/


All Articles