I have a file titled random.js, where i export a function called fetch(), which returns an integer of either 0 or 1, assigned to the variable x.
If I console.log it here, as follows:
export function fetch() {
let x = Math.floor(Math.random() * 2)
console.log(x)
//return x
}
And subsequently import the function into App.js, and call it there, as follows:
import { fetch } from "./random.js"
function fetch2() {
fetch()
//console.log(x)
}
It works as intended.
However, when I try to return the variable x from the function fetch() in random.js, as follows:
export function fetch() {
let x = Math.floor(Math.random() * 2)
//console.log(x)
return x
}
and try to read the variable x using function fetch2() in App.js, as follows:
import { fetch } from "./random.js"
function fetch2() {
fetch()
console.log(x)
}
I get an error telling me: 'x' is not defined no-undef
So how do I export the variable x from random.js, such that it is "readable" by App.js?
Two things.
fetch function must return a value.fetch2() you declare new x an pass the value from the fetch() to it.export function fetch() {
let x = Math.floor(Math.random() * 2)
console.log(x)
return x
}
import { fetch } from "./random.js"
function fetch2() {
let x = fetch()
console.log(x)
}