JS Hoisting
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking:
HackTricks Training GCP Red Team Expert (GRTE)
Basic Information
In the JavaScript language, a mechanism known as Hoisting is described where declarations of variables, functions, classes, or imports are conceptually raised to the top of their scope before the code is executed. This process is automatically performed by the JavaScript engine, which goes through the script in multiple passes.
During the first pass, the engine parses the code to check for syntax errors and transforms it into an abstract syntax tree. This phase includes hoisting, a process where certain declarations are moved to the top of the execution context. If the parsing phase is successful, indicating no syntax errors, the script execution proceeds.
It is crucial to understand that:
The script must be free of syntax errors for execution to occur. Syntax rules must be strictly adhered to.
The placement of code within the script affects execution due to hoisting, although the executed code might differ from its textual representation.
Types of Hoisting
Based on the information from MDN, there are four distinct types of hoisting in JavaScript:
Value Hoisting: Enables the use of a variable's value within its scope before its declaration line.
Declaration Hoisting: Allows referencing a variable within its scope before its declaration without causing a
ReferenceError
, but the variable's value will beundefined
.This type alters the behavior within its scope due to the variable's declaration before its actual declaration line.
The declaration's side effects occur before the rest of the code containing it is evaluated.
In detail, function declarations exhibit type 1 hoisting behavior. The var
keyword demonstrates type 2 behavior. Lexical declarations, which include let
, const
, and class
, show type 3 behavior. Lastly, import
statements are unique in that they are hoisted with both type 1 and type 4 behaviors.
Scenarios
Therefore if you have scenarios where you can Inject JS code after an undeclared object is used, you could fix the syntax by declaring it (so your code gets executed instead of throwing an error):
More Scenarios
References
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking:
HackTricks Training GCP Red Team Expert (GRTE)
Last updated