1

Variables defined inside if block, are accessible outside the if block also

console.log(name) // undefined

if (true) {
  var name = "harry"
  console.log(name) // harry
}

console.log(name) // harry

I got this:

if (true) {
  sayHello() // hello
  
  function sayHello() {
    console.log("hello")
  }

  sayHello() // hello
}

sayHello() // hello

Got this too.

But what's happening here

sayHello() // TypeError: sayHello is not a function

if (true) {
  sayHello()

  function sayHello() {
    console.log("hello")
  }

  sayHello()
}

sayHello()
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var have a look at this page – boxdox Aug 11 '21 at 06:00
  • With ES6 functions are now block scoped. "*variables defined inside if block, are accessible outside the if block also*" that is *only* true for `var` declared variables. – VLAZ Aug 11 '21 at 06:13
  • Have a look at the differences between strict and non-strict mode as suggested above and know the differences between var, let and const. Also, spend some time understanding how hoisting works in javascript. – nontechguy Aug 11 '21 at 06:17

2 Answers2

1

Hoisting of function declarations inside blocks has confusing semantics.

The last code example is similar to the code as shown below:

var sayHello1;
sayHello1();   

if (true) {
  let sayHello2 = function() {
     console.log("hello");
  }

  sayHello2();

  // assigned to outer variable at the place
  // of function declaration in your code
  sayHello1 = sayHello2;

  sayHello2();
}

sayHello1()

As seen in the above code, there are actually two variables in your code: one inside the block is a let declaration and one outside the block is a var declaration.

Variable defined outside the block is assigned the function declared inside the block at the place where it is actually defined in your code.

Invoking the outer sayHello1 variable as a function before it is assigned the function inside the block will throw an error.

Related Questions:

  1. Why does block assigned value change global variable?
  2. confused about function declaration in { }
  3. What are the precise semantics of block-level functions in ES6?
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

If we check the global execution context for the code, the "sayHello" on line 1 is hoisted and assigned as a variable and not as a function resulting in the type error. If we do the following modification in the code, we will get the sayHello as undefined and the code will not give the type error. Below is the code for the same.

console.log(sayHello) // prints "undefined" and not the type error.

if (true) {
  sayHello()

  function sayHello() {
    console.log("hello")
  }

  sayHello()
}

sayHello()