0

I have two JS files where I would like to access the variable associated with my JS Object.

rates.js

var CAD = {
    USD : 1.2727,
    EUR : 1.54,
    CNY : 0.20,
    BTC : 45139.58
    CZK : 0.059,
    GBP : 1.7338,
    CHF : 1.4345,
    JPY : 0.0123,
    AUD : 0.9827,
    PLN : 0.3405,
    ZAR : 0.0839
}
var CHF = {
    USD : 0.8911,
    EUR : 1.0766,
    CNY : 0.14,
    BTC : 32154.03,
    CZK : 0.041,
    GBP : 1.2086,
    CHF : 1,
    JPY : 0.0086,
    AUD : 0.685,
    PLN : 0.2375,
    ZAR : 0.0584
}

Second file where I would like to store a value in a variable:

dropdown.js

if(getTicker == "AUDCAD" ){
            var price = CAD.USD;
            alert(price);
}

I have used the following lines in my html file in an effort to connect the two with no success.

    <script src="rates.js"></script>
    <script src="dropdown.js"></script>
</body>
</html>

I am not using a server therefore I cannot make modules to import and export. Are there any other recommendations?

4
  • You can try attaching it into the global window object like so. window.CAD = {... And using it in dropdown.js as follows: var price = window.CAD.USD; Commented Jan 19, 2021 at 5:11
  • There is syntax error, a comma is missing after CZK property of CAD object in rates.js. Add a comma and try again. Commented Jan 19, 2021 at 5:19
  • @Philip this worked! Thank you so much. Commented Jan 19, 2021 at 5:41
  • As @Philip suggest you can do it using global variable with window, but it is discouraged. Because because they can be accessed from ANY function and you risk having multiple functions trying to read from and write to the same variables. Please see the modern approach I mention in my answer. Although using global variable with window is a common practice(unfortunately). Commented Jan 19, 2021 at 7:09

1 Answer 1

1

There is a type attribute in script tag. So you can set type as module in your dropdown.js file and export CAD & CHF from rates.js file and use them how you want. Here is the example:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script type="module" src="./dropdown.js"></script>
</body>
</html>

dropdown.js

import { CAD } from './demo.js'

console.log(CAD) // CAD obj

rates.js

const CAD = {
  USD: 1.2727,
  EUR: 1.54,
  CNY: 0.2,
  BTC: 45139.58,
  CZK: 0.059,
  GBP: 1.7338,
  CHF: 1.4345,
  JPY: 0.0123,
  AUD: 0.9827,
  PLN: 0.3405,
  ZAR: 0.0839,
}

const CHF = {
  USD: 0.8911,
  EUR: 1.0766,
  CNY: 0.14,
  BTC: 32154.03,
  CZK: 0.041,
  GBP: 1.2086,
  CHF: 1,
  JPY: 0.0086,
  AUD: 0.685,
  PLN: 0.2375,
  ZAR: 0.0584,
}

export { CAD, CHF }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.