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

164
Visualizações
Why the code execution result is 10 ? JS syntax

The code is:

x = 10;

if (x > 1) {
  var x = x + 1;
}

console.log(x);
var x;

The output of code execution is: 11

Why is it 11? , And Why is it not an error?

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

0

Description

var declarations, wherever they occur, are processed before any code is executed. This is called hoisting and is discussed further below.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#description

This means it does not matter where is your "var x", when this script is processed, the declaration will be the first.

about 4 years ago · Juan Pablo Isaza Relatório

0

You should understand how closures actually work.

// You define 'x' variable [1] in global scope 
x = 10;


if (x > 1) {
  // You define another one 'x' variable inside of 'if' scope
  // So here (inside of 'if') you will interact with this variable,
  // not with first one ([1])
  var x = x + 1;
}

// You code run out of 'if' so you're working with 
// global scope again, and your 'x' is first one [1]
console.log(x); // x = 10 still 
var 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