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

153
Visualizações
Variable will not become global

I have a variable in a function and I want to call it outside of the function however it says 'Name is not defined'. Please advise on how I can make this variable global.

n = Math.ceil(Math.random() * 80);
console.log(n)
function randomStarwars(){
    fetch('https://swapi.dev/api/people/'+n)
    .then(response => response.json())
    .then(data=> {
        var Name = data.name

    })
}
addEventListener("click", randomStarwars)
console.log(Name)
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You may want to take a look at variable scope.

The reason you can't access it it's because it's defined inside the .then() lambda function and can only be accessed there.

To have it available outside that function you need to declare it outside it:

n = Math.ceil(Math.random() * 80);
var Name = ""; // Here, for example
console.log(n)
function randomStarwars(){
    fetch('https://swapi.dev/api/people/'+n)
    .then(response => response.json())
    .then(data=> {
        Name = data.name; // Remove 'var', because it's already declared
    })
}
addEventListener("click", randomStarwars)
console.log(Name)

Update after your comment:

You don't see the value in your console.log because the value is assigned inside a Promise, which is never run right when declared.

To console.log the Name effectively, you need to chain another .then() and log it there:

n = Math.ceil(Math.random() * 80);
var Name = ""; // Here, for example
console.log(n)
function randomStarwars(){
    fetch('https://swapi.dev/api/people/'+n)
    .then(response => response.json())
    .then(data=> {
        Name = data.name; // Remove 'var', because it's already declared
    })
    .then(() => {
        console.log(Name) // This guarantees the value has been set, aside from any errors that might occur before
    })
}
addEventListener("click", randomStarwars)
console.log(Name) // This is executed before the Name is set
about 4 years ago · Juan Pablo Isaza Relatório

0

you must declare Variable before the fetch function

var Name = "";
    n = Math.ceil(Math.random() * 80);
console.log(n)
function randomStarwars(){
    fetch('https://swapi.dev/api/people/'+n)
    .then(response => response.json())
    .then(data=> {
         Name = data.name

    })
}
addEventListener("click", randomStarwars)
console.log(Name)
about 4 years ago · Juan Pablo Isaza Relatório

0

Define your variable outside your functions:

var global_Name; // this is your global variable 

n = Math.ceil(Math.random() * 80);
console.log(n)


function randomStarwars(){
    fetch('https://swapi.dev/api/people/'+n)
    .then(response => response.json())
    .then(data=> {
        global_Name= data.name // use it without var

    })
}
addEventListener("click", randomStarwars)
console.log(Name)

function2()
{
global_Name =  // use it without var
}

function3()
{
 global_Name = // use it without var
}
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