Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their respective scopes before code execution. This means that you can use these variables or functions before they are declared in your code. However, only the declarations are hoisted, not the initializations.
Let's see an example of how hoisting works with variables:
index.tsx68 chars3 lines
In the above code, even though myVariable
is declared after the console.log
statement, the declaration is hoisted to the top of the scope and the output will be "undefined".
A similar example with a function:
index.tsx99 chars6 lines
Again, the function declaration is hoisted to the top of the scope and can be called before it is defined.
It's important to note that only the declarations are hoisted, not the initializations. For example:
index.tsx102 chars3 lines
In this case, if you use let
to declare myVariable
, it is not hoisted to the top of the scope and trying to use it before its declaration will result in a "ReferenceError".
gistlibby LogSnag