AmAn KumAr
AmAn KumAr

Reputation: 386

Passing Variable in two JavaScript file

Is it possible to use the same variable which I have passed in another javascript file? For example, if in firstfile.js I declared const temp = 4; can I access temp in secondfile.js?

Upvotes: 1

Views: 835

Answers (5)

FZs
FZs

Reputation: 18619

The current best practice for the client-side is to use the ES6 modules. They separate their variables from each other, but you can export/import variables that are accessible to both files.

<script type="module" src="secondfile.js">
//firstfile.js
export const temp = 4
console.log('firstfile', temp) //4
//secondfile.js
import {temp} from './firstfile.js'
console.log('secondfile', temp) //4

If you have to support some old browsers (see on caniuse.com), you can still transcompile this code using something like Babel.


This solution also works in Node.js, however, you'll have to use the .mjs file extension or set "type": "module" in package.json (and the --experimental-modules flag if you're using version <14.0).

Upvotes: 1

James Ng
James Ng

Reputation: 136

As others have mentioned, the following is not recommended, as it is a bad practice. Global variables that are implicitly read can create problems. The import export patterns recommended in other answers are a better practice, as you have more explicit knowledge of where variables are coming from.

Only try out the following if you are curious to know about how browsers read script tags from top to bottom:

If you are using html script tags, you may have script files (the order matters):

<script src="firstFile.js"> </script>
<script src="secondFile.js"> </script>

As long as const temp = 4; is globally defined in firstFile.js, secondFile.js will have access to temp.

If you flipped the order:

<script src="secondFile.js"> </script>
<script src="firstFile.js"> </script>

secondFile.js will not have access to firstFile.js.

Upvotes: 1

Anwar Gul
Anwar Gul

Reputation: 683

In firstfile.js Export temp,

module.exports = { temp };

Get temp in Secondfile.js

const { temp } = require("pathOfFirstFile.js")

Upvotes: 3

ZecKa
ZecKa

Reputation: 2934

If you are using javascript in frontend you can use global window variable.

But be warn to not use reserved variable name, so you can prefix your variable.

// file1.js
window.myapp_temp = 4

// file2.js
console.log(myapp_temp)

keep in mind that using global variable is consider as a bad practice

Upvotes: 1

topher
topher

Reputation: 41

Yes, as long as they are both imported or declared in a single page.

Upvotes: 0

Related Questions