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

153
Vistas
var variable reassignment within function

I don't understand why a var variable can be reassigned within a function, but the change also applies outside of the function. Why/How?

var c = 1;

function Fn() {
c = 2;
}
Fn();
c; // 2

Why isn't the value 2 limited to the scope of the function? When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined, which is then changed to 2 once Fn() is called?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It applies outside the function because, inside the function, you are changing the variable.

You are not creating a new variable that exists only inside the function.


Why isn't the value 2 limited to the scope of the function?

You didn't use var, let, const or any other method to create a variable in the scope of the function.

You are accessing the variable you already created in the wider scope.


When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined, which is then changed to 2 once Fn() is called?

No. There isn't a new variable. There is only the c you already created outside the function.

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is a common complaint about javascript. Since you used "Var" it has a global scope, so even though you're within a new function when you use c=2 since it's already defined globally it's changed globally. Using "Let" helps define things local to the function and "const" defines globals as constants so they cannot be changed. This issue is particularly fun when you have two global variables with the same name in different JavaScript files and then reference both files to be used on a page. Globals should be used with caution.

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