0

Here I'm declaring a variable x as its initial value 10 and later declared a function x so it should overwrite x variable and it should log function x. But here it is throwing error as Uncaught TypeError: x is not a function.

function asas() {
    // 1
    var x = 10;     // CHECK
    
    // 2
    function x() {}
    
    // 3
    x();
    
    console.log(x);
}

asas();

whereas, If we don't assign anything to x as below snippet then it is taking a function as a value function x() {}. I don't understand why?

function asas() {
  // 1
  var x;            // CHECK

  // 2
  function x() {}

  // 3
  x();

  console.log(x);
}

asas();
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 2
    This has to do with how javascript handles `hoisting` - your function definitions get "hoisted" to the top of your context/scope (and only `function` declarations do that), so the declaration of your function happens _first_, with your variable overwriting it later. That variable is, indeed, not a function. It also has to do with the use of `var` (which is discouraged). Replace it with `let` or `const` and you should get an error, as you cannot _redeclare_ those in the same scope. – somethinghere Apr 03 '23 at 13:59

0 Answers0