The problem here is that you're not wrapping your code inside a function.
If you use an IIFE (Immediately Invocated Function Expression) the same code will work.
The reason your code fails is because you can't declare a constant in the same scope, if the constant/variable name is already taken.
You could have used var
instead of const
but that would have assigned to window.location
, effectively reloading the page and taking you to a 404 Page because that url doesn't exist.
That's why you should always write your code in an IIFE, to prevent global namespace pollution and nasty bugs that are hard to fix.
Here's the same code with an IIFE (added strict mode):
(() => { // 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);
})();
Or better yet:
{ // 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);
};
The use of the ES2015 block won't pollute the global scope, given that you'll be using only let
and const
(and not using var
)
Also, always remember that not all the browsers are supporting ES2015 syntax yet, so for now the code must be transpiled using Babel JS or similar tools.