Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this alert 5?

Tags:

javascript

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?

like image 582
savinger Avatar asked Sep 07 '12 19:09

savinger


People also ask

What is an alert 5?

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.

Why is it called Alert 5 aircraft?

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.

What does calling the ball mean?

(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.

What are alert fighters?

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.


3 Answers

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
like image 142
Frédéric Hamidi Avatar answered Nov 15 '22 01:11

Frédéric Hamidi


function x float to the top, so you assigning the function to 10

like image 33
yngccc Avatar answered Nov 15 '22 01:11

yngccc


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.

like image 27
Josh Mein Avatar answered Nov 15 '22 01:11

Josh Mein