Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
Returning a variable from an exported function (js)

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Two things.

  1. the fetch function must return a value.
  2. in the 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)
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!