• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

181
Vistas
Hoisting of "var" in javascript

I have read the following

Hoisting of var

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:

console.log (greeter);
var greeter = "say hello"

it is interpreted as this:

var greeter;
console.log(greeter); // greeter is undefined
greeter = "say hello"

So var variables are hoisted to the top of their scope and initialized with a value of undefined.

But what happens with this (undefined) They move at the top then why it is "undefined"?

if (true) {
  console.log(hi)
}
var hi = 1

If they are pushed up, they would also have to be "read" first, wouldn't they?

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Javascript only hoists declarations. The initialization is not hoisted.. The assignment only happens after your if condition.

This is also why some JS developers prefer let over var. If you use let, you will get a very clear error saying the variable cannot be

if (true) {
  console.log(hi);
}
let hi = 1;
//Uncaught ReferenceError: Cannot access 'hi' before initialization
almost 3 years ago · Juan Pablo Isaza Denunciar

0

The declaration is hoisted, but the assignment isn't.

It's really the same as the second example in your quote. So it's the equivalent of:

var hi;
if (true) {
  console.log(hi)
}
hi = 1

So hi is still undefined at the log statement.

This article has some good discussion and examples: https://blog.logrocket.com/demystifying-function-and-variable-hoisting-in-javascript/

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda