Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!