Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Global Variable typescript/ javascript

I want to declare a global variable with default value

const Months = [
{ name: 'January' },
{ name: 'February' },
{ name: 'March' },
{ name: 'April' },
{ name: 'May' },
{ name: 'June' },
{ name: 'July' },
{ name: 'August' },
{ name: 'September' },
{ name: 'October' },
{ name: 'November' },
{ name: 'December' }
];

and i want to use the Months Variable in multiple files. without redeclaring it again.
file1.tsx
Months.map(x => x.name);

file2.tsx
Months.map(x => x.name);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

how im going to do it?

>Solution :

Avoiding global variables can help to reduce bugs in your program and make your code easier to understand.

and i want to use the Months Variable in multiple files. without redeclaring it again.

This is exactly what is addressed by JavaScript modules, using the export and import keywords:

./constants.ts:

export const months = [
  { name: 'January' },
  { name: 'February' },
  { name: 'March' },
  { name: 'April' },
  { name: 'May' },
  { name: 'June' },
  { name: 'July' },
  { name: 'August' },
  { name: 'September' },
  { name: 'October' },
  { name: 'November' },
  { name: 'December' },
] as const;

./another_module.ts:

import { months } from './constants.js';

console.log(months.map(obj => obj.name)); // ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading