Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda