Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  197] [ 7]  / answers: 1 / hits: 20093  / 7 Years ago, fri, april 21, 2017, 12:00:00

I write this simple program to update value of JS hoisting. But as per my understanding global x need to update, but It is not updating.



x = 5;
var w = function(){
x = 7
var x;
console.log(x);
x = 10;
console.log(x);
};
w();
console.log(x);


Output:




  • 7

  • 10

  • 5



Could anyone explain in more details why it did not update global x ?



Javascript work on reference of values so when I write x = 7, it should be update the global x. But it din't!
So I just want to why x =7 doesn't work ?



Thanks!


More From » javascript

 Answers
49

Because you redeclared x in your function's local scope. That's the one you assigned 10 to, instead of the global one.



Ditch the var x; and it will work.



x = 5;
var w = function(){
x = 7
// var x;
console.log(x);
x = 10;
console.log(x);
};
w();
console.log(x);


That being said, what's probably baffling you is hoisting




Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).




x = 5;
var w = function(){
x = 7
var x; // this is moved to the top of the local scope
console.log(x);
x = 10;
console.log(x);
};
w();
console.log(x);

[#58054] Thursday, April 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchellg

Total Points: 235
Total Questions: 117
Total Answers: 106

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;