Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda