Curious bit of code here...
var x = 5;
function fn() {
x = 10;
return;
function x() {}
}
fn();
alert(x);
Here's the jsFiddle
Is function x() {}
called at all after return
?
Why not alert 10?
alert five (uncountable) (military, slang) On an aircraft carrier, the state where fighters and crew are on guard, standing by in the aircraft, strapped in and ready to be launched in five minutes or less.
Ready Five, also referred to as Alert Five in the film Top Gun, is a condition of high alert for aircraft crews on the flight deck of an aircraft carrier, in which they are ready to launch within five minutes.
(US) When landing on a US aircraft carrier: to sight the lights from the multi-colored optical landing system that shows a pilot to be on the correct approach path or how to correct the approach path.
Alert fighters are a group of Vipers "standing by" within a battlestar's launch tubes with their pilots in or very near their cockpits in preparation for a quick launch, and are analogous to modern day "alert five" aircraft.
function x() {}
is hoisted to the start of fn
's scope, and this effectively makes x
a local variable before x = 10;
is evaluated.
The function is not set to 10
.
Update: The sentence above is wrong. x
is actually set to 10
. var
is not used to declare it, but even if it was, the last sentence in the quote below only refers to the declaration part of the name x
, not its assignment to 10
.
From MDN (emphasis mine):
function
Three forms with different scope behavior:
- declared: as a statement at the parent function top-level
- behaves like a var binding that gets initialized to that function
- initialization "hoists" to the very top of the parent function, above vars
var
- function-scoped
- hoist to the top of its function
- redeclarations of the same name in the same scope are no-ops
function x float to the top, so you assigning the function to 10
You are declaring function x within fn; therefore, you are using the locally scoped version of x. It doesn't matter at what point the function x is declared. What you are actually doing when you set x to 10 is you are setting the function of x to 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With