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

213
Visualizações
Javascript var, let and function

    let x = '1'
    function first(){
        console.log(x)
    }
    x='2'
    function second(){
        let x='3'
        first()
    }
    second()

My question is , why is the answer '2' instead of '3'? I know let is block scope and var is function scope,but I just do not get this right. Please help me here, many thx!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You are assigning 3 to a local variable, it only has an effect inside the second function

This example works:

let x = '1'

function first(){
    console.log(x)
}

x='2'

function second(){
    x='3'
    first()
}

second()

about 4 years ago · Juan Pablo Isaza Relatório

0

initially the function first has no idea what x is about. so it automatically searched in the upper scope.

gladly, on the global scope there is x definition.

Therefore, as this script got initialized, the function console.log in function first reserve the memory address of x, and watches that global variable all along.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is because of shadowing.

In JavaScript, variables with the same name can be specified at multiple layers of nested scope. In such a situation, local variables gain priority over global variables. If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function or block.

And in your case, there is no local variable define inside your first() function so it will take the value of x = 2 of the global variable.

let x = '1'

function first() {
  console.log(x)
}
x = '2'

function second() {
  let x = '3'
  first()
}
second()

See the below code, If you've declared x=4 inside first() then it will return the value 4 instead of 2

let x = '1'

function first() {
  x = '4'
  console.log(x)
}
x = '2'

function second() {
  let x = '3'
  first()
}
second()

Check out this if you want to know more about JavaScript Variable Scope and Hoisting: https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

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