Module 04
Branching
Bitcoin Script has no loops and no goto — but it does have conditionals. OP_IF lets a script take different paths based on a value on the stack, enabling scripts that respond to their inputs.
What you'll learn
- →Write OP_IF / OP_ELSE / OP_ENDIF blocks
- →Use OP_NOTIF for inverted conditions
- →Explain how the condition stack tracks nested branches
- →Apply OP_VERIFY and OP_RETURN for guard clauses
01
OP_IF / OP_ELSE / OP_ENDIF
OP_IF pops the top item. If it's truthy, the block between IF and ELSE executes. If falsy, the ELSE block executes (if present). OP_ENDIF closes the block. This is the only form of branching in Bitcoin Script.
The condition value is consumed — it's popped from the stack before any branch executes.
OP_IF (true branch)Condition is 1 (truthy) → the IF branch runs, pushing 7.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_IF (false branch)Condition is 0 (falsy) → the ELSE branch runs, pushing 9.
↑ top of stack
nothing here yet
press Step or Run to push an item
Branching in Lightning
02
OP_NOTIF and nesting
OP_NOTIF is the mirror image of OP_IF: it executes its block when the condition is falsy. Conditionals can be nested — each OP_ENDIF closes the innermost open block.
OP_NOTIFCondition is 0 (falsy) → the NOTIF block runs, pushing 5.
↑ top of stack
nothing here yet
press Step or Run to push an item
Nested OP_IFTwo nested conditionals. Both conditions are true → innermost IF branch runs, pushing 16.
↑ top of stack
nothing here yet
press Step or Run to push an item
03
OP_VERIFY and OP_RETURN
OP_VERIFY pops the top item and immediately fails the entire script if it's falsy. It's the assertion opcode — used when you need to guarantee a condition is true before proceeding. Many opcodes end with VERIFY as a suffix (e.g. OP_EQUALVERIFY) — these are shorthand for running the base opcode then verifying the result.
OP_RETURN unconditionally fails the script and marks the output as unspendable. It's used in data-carrier outputs for embedding metadata.
OP_VERIFY (pass)5 == 5 → OP_VERIFY passes → OP_1 pushes true. Script succeeds.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_VERIFY (fail)5 ≠ 6 → OP_VERIFY fails the script immediately.
↑ top of stack
nothing here yet
press Step or Run to push an item
OP_RETURN? Try OP_1 OP_RETURN OP_2 below.Ctrl+Enter to run
↑ top of stack
nothing here yet
press Step or Run to push an item
04
Your turn
Conditional result
Ctrl+Enter to check