0

What is the following statement doing, and why use const vs var?

const { SearchIcon } = myApp.icons;

For context, I am learning Vue and new to Javascript. I saw this in an example. The SearchIcon is an icon that is being imported from heroicons, MyApp.icons is being defined in a different script file like this:

window.MyApp = {
    app: null,
    icons: {},
...
Brian W
  • 5
  • 3
  • 3
    This syntax is called `destructuring`. You can read about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring – mr rogers Apr 01 '22 at 20:41
  • it's a shorthand for `const SarchIcon = myApp.icons.SearchIcon;` – Robin Zigmond Apr 01 '22 at 21:06
  • 1
    In relation to: "why use const vs var". In Short, `const` is block-scoped and can't be reassigned. Since ES6 you should always consider using `let` and `const` instead of `var` Here is a longer explanation about the differences between const, let and var: [https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Slin F Apr 02 '22 at 08:57

1 Answers1

0

Looks like your issue is that you're storing MyApp under window, but then trying to access it directly. You've also got a capital M in the definition, and a lowercase when your accessing it.

Here's a working example:

window.MyApp = {
  app: null,
  icons: {
    SearchIcon : 'Hello!'
  },
};

const { SearchIcon } = window.MyApp.icons;

console.log(SearchIcon);

For more info, see the docs on object destructuring.

Hope that helps :)

Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64