Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: Cannot access 'stocks' before initialization

I'm trying to import an object into another JS file, and I keep getting this error, Uncaught ReferenceError: Cannot access 'stocks' before initialization. I've declared stocks, and I've imported it correctly, so I can't see what I did wrong. Any help is much appreciated. Thanks.

In the stocks file:

export const stocks = {
    megaCorp: {
        name: 'Mega Corporation',
        value: decideStockValue(),
        portIn: 0,
        document: "mega"
    },

    lunaBake: {
        name: "Luna Baking",
        value: decideStockValue(),
        portIn: 1,
        document: "luna"
    },
}

And in the user file :

import { stocks } from "./stocks.js";

export let user = {
    money: 2000,
    portfolio: [0, 0, 0, 0]
}

function getValue () {
    let value = user.money;
    let cannon = stocks.cannonRock.value * user.portfolio[0];
    let alpha = stocks.alphaComp.value * user.portfolio[1];
    let luna = stocks.lunaBake.value * user.portfolio[2];
    let mega = stocks.megaCorp.value * user.portfolio[3];
    value += cannon;
    value += alpha;
    value += luna;
    value += mega;
    return value;   
}

user.value = getValue();
like image 578
User 10 Avatar asked Mar 03 '23 09:03

User 10


1 Answers

Again Looking at the code it seems syntactically fine, so this is not an answer but i rather want to share a snippet of code to see how it behaves.

The error you shared Uncaught ReferenceError: Cannot access 'variable_name' before initialization is thrown when a lexical variable was accessed before it was initialized ( what is known as a temporal dead zone error), however in the code you share there is nothing that should throw this error.

for example this code will throw this error

const x = 3
function a(){
    console.log(x)
    const x = 5;
}
a()

Assuming indeed that the error originated from the user file, then the following code might solve it. In the code u had getValue was a function expression that should be hoisted ( which again should be fine), but it could be that a bundler you are using is misbehaving.

import { stocks } from "./stocks.js";

const getValue = (stocks, money, portfolio) => {
  let value = money;
  let cannon = stocks.cannonRock.value * portfolio[0];
  let alpha = stocks.alphaComp.value * portfolio[1];
  let luna = stocks.lunaBake.value * portfolio[2];
  let mega = stocks.megaCorp.value * portfolio[3];
  value += cannon;
  value += alpha;
  value += luna;
  value += mega;
  return value;
};

const money = 2000;
const portfolio = [0, 0, 0, 0];
export const user = {
  money,
  portfolio,
  value: getValue(stocks, money, portfolio),
};


like image 146
ehab Avatar answered Mar 05 '23 15:03

ehab