Reputation: 509
I've been refactoring my App.js file and taking some functions out into a file called utilities.js. Each function has an export and my App.js has the requisite import. However, I am getting some 'myVariable' is not defined
errors for the utilities.js file. I figure this is because I am declaring the variable outside of the App() function in my App.js file, and so if you look at the utilities.js file in isolation, the variables haven't been declared. This pieceTable variable is also used in other functions in App.js.
How do you deal with this situation?
Example:
utilities.js file
export const findPieces = piece => {
pieceTable = [];
// blah blah
}
App.js file
import {findPieces} from './utilities'
let pieceTable=[];
function App() {
const findDraught = findPieces('King')
}
I get a "Failed to compile" error for this type of scenario, saying 'pieceTable' is not defined in utilities.js
Upvotes: 0
Views: 1049
Reputation: 11740
When you say let pieceTable=[];
you are explicitly making pieceTable
a variable with scope local to the module, i.e. not a global.
If you had just referred to pieceTable
you would be assigning a property to the top-level scope object which is window
(in a browser JavaScript context). You can refer to it explicitly with: window.pieceTable
.
(FYI, in node.js it would be global.pieceTable
. Read why.)
Globals are passé and I don't recommend using one in your case.
Choose an owning module for pieceTable
and have that module export it. Then have every other module that needs to refer to pieceTable
import it. This is making use of the module mechanism rather than the global mechanism.
Design your functions so that they are passed in the value of pieceTable
(or an object that has pieceTable
as a property) as an argument to the function rather than relying on getting a singleton or global. This will make your functions easier to test as well and eliminate confusing global side effects.
Upvotes: 1
Reputation: 769
Well it's not defined in utilities.js
because there's not a let
or const
.
If you don't want to redefine it in the utilities function, then you need to pass in the pieceTable
when you call findPieces
.
Upvotes: 0
Reputation: 509
My functions are not pure. I need to pass in the pieceTable as an argument when calling it, and it avoids all these issues. Don't have my utilities.js file rely on global variables in another file. Pass in arguments to these utility functions instead.
Upvotes: 0