0

Question

I'm trying to understand why the following three JavaScript examples produce different outputs, even though they all seem to involve function hoisting. Shouldn't the outputs be the same based on how function hoisting works?

Example 1

var a = 0;
console.log("1 a:", a);
if(true){
    a = 1;
    function a() {}
    a = 5;
    console.log("2 a:", a);
}
console.log("3 a:", a);

The output is:

1 a: 0
2 a: 5
3 a: 1

This has been verified.

Example 2

var a = 0;
console.log("1 a:", a);
if(true){
    a = 1;
    a = 5;
    console.log("2 a:", a);
    function a() {}
}
console.log("3 a:", a);

The output is:

1 a: 0
2 a: 5
3 a: 5

This has been verified.

Example 3

var a = 0;
console.log("1 a:", a);
if(true){
    function a() {}
    a = 1;
    a = 5;
    console.log("2 a:", a);
}
console.log("3 a:", a);

The output is:

1 a: 0
2 a: 5
3 a: f a() {}

This has been verified.

What I've Tried

I've read up on function hoisting in JavaScript, but these examples are throwing me off. I'm not sure why they don't produce the same output based on my understanding of function hoisting.

Questions

  1. How do these examples differ in the context of function hoisting?
  2. Why is the output different in each example?

Any insights would be much appreciated!

Keith
  • 22,005
  • 2
  • 27
  • 44
klion
  • 37
  • 3
  • Relevant, maybe a dupe: [What are the precise semantics of block-level functions in ES6?](https://stackoverflow.com/q/31419897) – VLAZ Aug 21 '23 at 12:26
  • this is because you forget `function a() {}` is also `a = function() {}` or `var a = function a() {}` depending on the scope. – Mister Jojo Aug 21 '23 at 12:31
  • @MisterJojo I don't think so, you can check this ` var a = 0; console.log("1 a:", a); if(true){ a = 1; var a = function() {} a = 5; console.log("2 a:", a); } console.log("3 a:", a); ` it will output ` 1 a: 0 2 a: 5 3 a: 5 ` – klion Aug 21 '23 at 12:41
  • anyway giving identical names to variables and functions is one of the worst things to do in programming. – Mister Jojo Aug 21 '23 at 12:58
  • 2
    Always use `'use strict';`, Javascript has ben around for a long time, there are legacy reasons for all of this, trying to understand why some legacy / edge cases for the `var` / `function` act the way they do won't help with modern coding. Also `var` is something that not really required these days, `let / const` are generally adviced. – Keith Aug 21 '23 at 13:07

0 Answers0