javascripthoistingjavascript-function-declaration

Why is it possible to assign to properties of a function before its declaration?


This piece of code

uniqueInteger.count = 0;
function uniqueInteger() {
  return uniqueInteger.count++;
}
console.log(uniqueInteger());
console.log(uniqueInteger());

produces the following output:

0
1

How it happens that this code is executed, as when assigning count attribute on the first line uniqueInteger is not declared yet?


Solution

  • This is happening because of function hoisting

    Basically when you declare a function, it's conceptually moved to the top of your code (although this is not what the browser is literally doing, check the previous docs for more information about that), therefore, we can rewrite your code to the following flow:

    function uniqueInteger() {
        return uniqueInteger.count++
    }
    uniqueInteger.count = 0;
    console.log(uniqueInteger()) // 0
    console.log(uniqueInteger()) // 1