1

I'm a little bit confused with this response.

foo = "ffsds";
function bar() {
    return foo;
    var foo = 10;
    function foo() { return "func"; };
    foo = "5353";
}
console.log(typeof bar());

After executing this code I have seen that it return a function. But it is not clear to me. Why does it not return 10?

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Elham Ajdari
  • 185
  • 9
  • 1
    This is due to _hoisting_. Not quite a duplicate question but close: [Javascript function scoping and hoisting](https://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting) – blex Jan 08 '21 at 11:33

2 Answers2

4

This is because of JS hoisting. As mentioned here,

Order of precedence

It’s important to keep a few things in mind when declaring JavaScript functions and variables.

  1. Variable assignment takes precedence over function declaration
  2. Function declarations take precedence over variable declarations

Function declarations are hoisted over variable declarations but not over variable assignments.

Notice this part specially,

Function declarations are hoisted over variable declarations but not over variable assignments.

After hoisting your code will execute like:

foo = "ffsds";
function bar() {
    function foo() { return "func"; };
    return foo;
    foo = 10;
    foo = "5353";
}
alert(typeof bar());
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
2

This works because of hoisting. Function declarations "executes" first. Than all other assignments.

But you wrote a return on top so only function declaration works, that's why you get function instead of other value.

Here is a simple example

function test() {
  return a; // returning
  var a; // variable declaration, works despite the return, but a equals function a because function declarations take precedence over variable declaration
  function a() {
    return 1;
  } // function declaration, works despite the return, override a to be a function
  a = 33; // function assignment - not works because return executes before assignments. a is still the function
}

console.log(test());
Drag13
  • 5,859
  • 1
  • 18
  • 42