简体   繁体   中英

why code after the return statement is reachable in javascript

I am new in JavaScript , and i have one confusion.
As we always taught that code after the return statement is unreachable.
But this is not true in below case and i am not able to understand why its so.

function foo() {

  //define bar once
  function bar() {
      return 3;
  }

  //redefine it
  function bar() {
      return 8;
  }

  //return its invocation
  return bar(); //8
}
alert(foo());

http://jsfiddle.net/jainhimanshu/euga4mcy/
and output is 8 but it should be 3.

So can anyone clear me the concept.

This is because you've to call the function to get the return value from it.

The function bar is not called, it is only defined.

So, when the function foo() is called

return bar();

from foo is executed and 8 is returned.

The Compiler sees the foo as follow(after overriding the bar ):

function foo() {
    function bar() {
        return 8;
    }

    return bar();
}
alert(foo());

When return bar() is reached, the function bar is called and it's value is returned.

After invocation of bar

function foo() {
    return 8;
}
alert(foo());
function foo(){
  // ....
}

creates new Function object , and assignees name foo to it. It is still no where called, just created, so any return statement will not be triggered.

When inside this function you create new Functions , like

function foo(){
  function bar() {
    return 3;
  }
  return 4;
}
// after you execute foo
console.log(foo()); // will log 4

But very important that inside this lexical scope, function bar is created, but no where executed. See also Lexical scope

But when you have this

function foo(){
  function bar(){
    return 3;
  }
  function bar() {
    return 8;
  }
  return bar();
}
// after you execute foo
console.log(foo()); // will log 8

When you execute function foo inside global scope, it creates Function object named bar , then it creates new Function object named bar , the old one is redefined, same as assigning new value to variable , value changes, but in this context function body that is assigned to Function name has change.

Because your function foo has return keyword, it returns that value. Value that it returns is value that returns function bar , as return bar(); will execute function bar and return value it receives from function bar , in example it is value 8.

Compare variable redefinition with function redefinition

var a;
a = "some string";
a = 5; // a has value 5, no mater older values
// same goes for functions
function bar(){ .... }
function bar(){ .... }
function bar(){ .... }
// invoke bar
bar(); // last function bar will be executed, no mater other function's bar definitions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM