0

may i know how this code execute?

function scope() {
  return hosting;

  function hosting() {
    var hosting = '15';
  }
  var hosting = 12;

}

console.log(typeof scope())

here this code return function, we now js engine will move the declaration to top so we get function,

function scope() {
  return hosting;

  var hosting = 12;
}

console.log(typeof scope())

but now why its not return number?, but i know we need to use let to avoid this

Ivar
  • 6,138
  • 12
  • 49
  • 61
Selva Ganapathi
  • 982
  • 10
  • 21
  • 1
    It's [hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) (not hosting). But there is really no good reason to still use `var` instead of `let` and `const`. – Andreas Jun 09 '20 at 13:27
  • oops my bad, i am stuck with legacy code – Selva Ganapathi Jun 09 '20 at 13:31

3 Answers3

1

When JS hoists a function it will know to return the actual function, but when it's a variable declaration it hoists it with undefined as value. And unless the actual line of assignment is reached, it won't have the value.

DSCH
  • 2,146
  • 1
  • 18
  • 29
1

It doesn`t return number 12 because hoisting works only for declarating the actual variable, not to assign it a value.

This means that your code looks like this for compilator:

function scope() {
    var hosting;
    return hosting;

    hosting=12;

}

Also please remember that everything after return is not executed.

Gesha
  • 703
  • 4
  • 7
0

If you want the console.log to return number you should put the hosting declaration above the return like that:

function scope() {
  var hosting = 12;
  return hosting;

 
}

console.log(typeof scope())
Bar Levin
  • 205
  • 1
  • 12