Tutorial

Pine Script switch Statement: Cleaner Than Nested if

Learn both forms of the Pine Script switch, how it returns a value, and when it beats a nested if chain, with complete v6 examples.

•11 min read

You have a script with an input that lets the user pick a moving average type, and somewhere around line 40 there is a block that looks like a staircase. An if, then an else if, then another else if, each one indented a little further than your patience. It works, but every time you want to add a fifth option you have to read the whole chain again to remember which branch does what. The switch statement exists for exactly this situation, and in Pine Script v6 it does more than most people use it for.

This guide covers both forms of switch, the rules that decide which branch runs, the way it returns a value, and the handful of mistakes that make a switch compile but behave oddly. Every code block is complete Pine Script v6, so you can paste it into the Pine Editor and read the result on the chart.

Why a long if chain gets hard to read

A chain of if and else if blocks asks you to read every condition from the top until one matches. When all the conditions test the same variable against different values, the repetition is the real cost. You write maType == four times, and a typo in the third one will not raise an error. It will just never match.

Here is the version most scripts start with. It picks a moving average from a dropdown input and assigns the result to a variable declared before the chain.

pine
//@version=6
indicator("Nested if baseline", overlay = true)

maType = input.string("EMA", "MA type", options = ["SMA", "EMA", "WMA", "RMA"])
len = input.int(20, "Length", minval = 2)

smaV = ta.sma(close, len)
emaV = ta.ema(close, len)
wmaV = ta.wma(close, len)
rmaV = ta.rma(close, len)

float ma = na
if maType == "SMA"
    ma := smaV
else if maType == "EMA"
    ma := emaV
else if maType == "WMA"
    ma := wmaV
else
    ma := rmaV

plot(ma, "Moving average", color.orange, 2)

Notice two things about this code. First, the variable ma has to be declared outside the chain with a type and a placeholder value, then reassigned with := inside each branch. That is boilerplate that carries no meaning. Second, the four moving averages are calculated before the chain, not inside it. That is deliberate and it matters for reasons covered later, because functions like ta.ema need to see every bar to keep their history correct.

The switch with an expression

The first form of switch takes an expression on the header line, then lists the values it should be compared with. Each case is a value, an arrow =>, and what to do when the value matches. The branch whose value equals the expression wins, and the others are skipped.

pine
//@version=6
indicator("Switch MA picker", overlay = true)

maType = input.string("EMA", "MA type", options = ["SMA", "EMA", "WMA", "RMA"])
len = input.int(20, "Length", minval = 2)

smaV = ta.sma(close, len)
emaV = ta.ema(close, len)
wmaV = ta.wma(close, len)
rmaV = ta.rma(close, len)

ma = switch maType
    "SMA" => smaV
    "EMA" => emaV
    "WMA" => wmaV
    => rmaV

plot(ma, "Moving average", color.orange, 2)

The placeholder variable is gone. A switch is an expression, which means it produces a value, and you can assign that value straight to ma. The last line, an arrow with nothing in front of it, is the default branch. It runs when no other case matched. In this script the dropdown only allows four strings, so the default will take the last option, but a default is still a good habit because it makes the intent explicit and protects you when someone edits the options list later.

The comparison is an equality test. "EMA" => emaV means "if maType == "EMA"". There is no pattern matching, no ranges, and no way to list two values in a single case. Each case compares exactly one value.

The switch without an expression

The second form leaves the header empty. Instead of comparing everything to one value, each case carries its own boolean condition, and Pine Script runs the first case whose condition is true. This is the replacement for a chain that tests different things in each branch.

pine
//@version=6
indicator("RSI reading with switch")

rsiLen = input.int(14, "RSI length", minval = 2)
r = ta.rsi(close, rsiLen)

zoneColor = switch
    r >= 70 => color.red
    r >= 55 => color.orange
    r > 45 => color.gray
    r > 30 => color.teal
    => color.green

plot(r, "RSI", zoneColor, 2)
hline(70, "Upper", color.red)
hline(30, "Lower", color.green)

The order of the cases is part of the logic here. A reading of 72 satisfies r >= 70 and also r >= 55, but only the first one runs. That is why the cases go from the most specific threshold to the least specific. If you reversed the top two lines, no bar would ever be colored red, because every reading above 70 is also above 55 and the orange case would claim it first. With a long if chain the same ordering rule applies, but the layout of a switch makes the thresholds line up in a column where you can check them at a glance.

This form also tidies up classification logic that would otherwise need nested ternaries. A ternary with three levels, a ? x : b ? y : c ? z : w, is legal but hard to read, and a switch says the same thing with a case per line.

A switch returns a value, and the types must agree

Because the switch is an expression, every branch has to produce a value of a compatible type. In the moving average example every branch is a float series. In the RSI example every branch is a color. If one branch returned a float and another returned a string, the compiler would refuse the script, because it cannot decide what type ma or zoneColor should have.

What happens when no case matches and there is no default? The switch returns na. For a numeric result that is usually harmless, but it can leak into later calculations quietly, since na propagates through arithmetic without raising an error. If you are not sure that your cases cover every input, add a default branch, even if it only returns na on purpose so that a reader can see the decision was made. The article on how Pine Script handles na explains why silent propagation causes so many hard-to-trace bugs.

A switch can also be used purely for its effects, with no result assigned. In that case the branches do not need to agree on a type. This is common for counters and state updates, where each case changes a variable and nothing is returned.

pine
//@version=6
indicator("Bar kind counter", overlay = true)

var int upBars = 0
var int downBars = 0
var int flatBars = 0

switch
    close > open => upBars += 1
    close < open => downBars += 1
    => flatBars += 1

var table info = table.new(position.top_right, 1, 3)
if barstate.islast
    table.cell(info, 0, 0, "Up bars: " + str.tostring(upBars))
    table.cell(info, 0, 1, "Down bars: " + str.tostring(downBars))
    table.cell(info, 0, 2, "Flat bars: " + str.tostring(flatBars))

The three counters use var, so they keep their values from bar to bar instead of resetting. Each bar lands in exactly one case, and the table on the last bar prints the totals. If var is new to you, var, varip, and persistent state in Pine Script goes through how it behaves on historical and real-time bars. The counts here describe what already happened on the chart. They say nothing about what the next bar will do.

No fallthrough, and what that means for you

If you have used switch in C, JavaScript, or Java, you may be waiting for the break keyword. There is none, because Pine Script does not fall through. Once a case matches and runs, the switch is finished. You cannot accidentally run two branches by forgetting a break, which removes one of the most common bugs in those languages.

The flip side is that you cannot deliberately share a branch between several values by stacking them, as you would in other languages. To make two values do the same thing, use the expression-less form and combine the conditions yourself.

pine
//@version=6
indicator("Shared branch", overlay = true)

tfChoice = input.string("Fast", "Speed", options = ["Fast", "Quick", "Normal", "Slow", "Glacial"])

length = switch
    tfChoice == "Fast" or tfChoice == "Quick" => 9
    tfChoice == "Normal" => 21
    => 55

plot(ta.sma(close, length), "SMA", color.blue)

Here "Fast" and "Quick" share one branch because the condition joins them with or. This is also the moment to remember how and and or evaluate in v6: the right side is only evaluated when it has to be. For plain string comparisons that changes nothing, but if a condition contains a function call, the lazy evaluation rules for and/or decide whether that call runs on every bar.

One more difference from the C family: the cases are not limited to constants. The value on the left of an arrow can be any expression, including a variable or a function result. In the expression form, Pine Script evaluates the cases from the top and compares each to the header value until one is equal.

Why indicator calls belong outside the branches

Back to the detail from the first example. All four moving averages were calculated before the chain, and the same is true in the switch version. The reason is how Pine Script runs: a script executes once per bar, and many functions in the ta namespace compute from their own previous values. When you call ta.ema(close, len) inside a branch that only runs on some bars, the function skips the bars where that branch was not taken, and its internal history has gaps. The result on the chart differs from what you expected, and the compiler warns about it for this exact reason.

The safe pattern is to compute every candidate on every bar, then let the switch choose among the results. It costs a few extra calculations, which are cheap, and it keeps each series consistent. The execution model article walks through the bar-by-bar loop that causes this, and the type system guide explains why the chosen value is a series even when the input is a simple string.

The same reasoning applies to request.security calls and to anything that depends on history. Calculate first, choose afterward.

Switching on an enum

Strings work, but they have an obvious weakness: a typo in a case label is a silent bug. Pine Script v6 has enums, a fixed set of named values, and a switch over an enum reads cleanly while giving the compiler something stronger to check than free text.

pine
//@version=6
indicator("Enum switch", overlay = true)

enum AvgKind
    sma = "SMA"
    ema = "EMA"
    wma = "WMA"
    rma = "RMA"

kind = input.enum(AvgKind.ema, "MA type")
len = input.int(20, "Length", minval = 2)

smaV = ta.sma(close, len)
emaV = ta.ema(close, len)
wmaV = ta.wma(close, len)
rmaV = ta.rma(close, len)

ma = switch kind
    AvgKind.sma => smaV
    AvgKind.ema => emaV
    AvgKind.wma => wmaV
    AvgKind.rma => rmaV

plot(ma, "Moving average", color.orange, 2)

The dropdown in the settings panel is built from the enum, so the list of choices and the list of cases come from one definition. Add a fifth kind to the enum and you will see at once that the switch needs a matching case. The enums article covers the syntax in more depth, including how to use enums for state machines.

When an if is still the better tool

A switch is not a universal replacement. Use if when you have a single condition and a single action, because a one-case switch is just a longer way to write it. Use if when the branches need to run several unrelated statements and then continue, since a switch is built around producing or choosing one thing. And keep if when conditions truly overlap in ways you want to reason about separately, instead of encoding priorities in the order of lines.

A reasonable rule of thumb: when you notice you are comparing the same value over and over, or when the chain exists to pick one result out of several, reach for a switch. Otherwise leave the if alone. Refactoring a working script for style alone is not worth breaking it, so after any rewrite, compare the plotted output of the old and new version on the same chart range before you delete the original.

Common mistakes to look for

The first is the case order mistake in the expression-less form. Because the first true condition wins, a broad condition placed above a narrow one makes the narrow one unreachable. When a case never seems to trigger, check what sits above it.

The second is the type mismatch. A branch that returns 0 next to one that returns close can be a problem when one is an integer and the other a float series, depending on how the result is used. If the compiler complains about types, make the branches explicitly the same type, for instance by writing 0.0.

The third is the missing default. An unmatched switch gives na, and a plot of na simply draws nothing, so the bug looks like an empty chart instead of an error. When a switch driven result vanishes, test the default first.

The fourth is expecting a multi-value case. There is none. Combine conditions with or in the expression-less form.

Refactor your own condition chain with PineScripter

If you already have a script full of staircase conditions, you do not need to rewrite it by hand. In PineScripter's AI editor, paste the script and ask for the change in plain English, for example "Replace the nested if chain that picks the moving average with a switch, and keep the calculations above it". The editor works on Pine Script v6, changes only the affected lines instead of rewriting the whole file, and shows a line-by-line Code Changes view so you can see exactly what moved. Every script is run through a linting check that follows TradingView's compile rules, and when it finds an error the editor fixes it on its own. If you want to check a refactor yourself, the free Pine Script validator runs in your browser and needs no account.

If you are writing prompts for larger rewrites, how to describe a complex indicator so the AI gets it right has the structure that works. You can see the plans on the pricing page.

PineScripter is an independent coding tool for Pine Script. It is not a broker, a trading platform, or financial advice, and nothing in this article predicts or promises any trading result. The code examples show how a language feature works.

Frequently asked questions

Does Pine Script have a switch statement?

Yes. Pine Script v6 has a switch with two forms: one compares an expression to each case value, the other has no header and runs the first case whose condition is true.

Does a Pine Script switch fall through like in C or JavaScript?

No. Only the first matching case runs and there is no break keyword. To share one branch between values, use the header-less form and join conditions with or.

What does a switch return when no case matches?

It returns na unless you add a default branch, written as an arrow with no value in front of it. Add a default when your cases might not cover every input.

Can I call ta functions inside switch branches?

It is better not to. Functions such as ta.ema need to run on every bar to keep their history consistent, so calculate each candidate before the switch and let the switch choose among the results.

Can I use a switch with an enum in Pine Script v6?

Yes. Declare an enum, expose it with input.enum, and switch on the value with one case per member. The list of choices and the cases then share one definition.

Describe your indicator in plain English and get Pine Script that compiles →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.