Say I have a module (./my-module.js
) that has an object which should be its return value:
let values = { a: 1, b: 2, c: 3 }
// \"export values\
I suggest the following, let's expect a module.js:
const values = { a: 1, b: 2, c: 3 };
export { values }; // you could use default, but I'm specific here
and then you can do in an index.js:
import { values } from "module";
// directly access the object
console.log(values.a); // 1
// object destructuring
const { a, b, c } = values;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
// selective object destructering with renaming
const { a:k, c:m } = values;
console.log(k); // 1
console.log(m); // 3
// selective object destructering with renaming and default value
const { a:x, b:y, d:z = 0 } = values;
console.log(x); // 1
console.log(y); // 2
console.log(z); // 0
More examples of destructering objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring