# Unexpect differences between calling \ifmmode from within a command and outside a command [duplicate]

In answering another question regarding testing for math mode, I proposed the following command

\newcommand{\testa}{%
\ifmmode
^{12}\text{CO(1-0)}%
\else
$^{12}$CO(1-0)%
\fi
}


But @egreg pointed out that I should be writing either:

\newcommand{\egrega}{%
\relax
\ifmmode
^{12}\text{CO(1-0)}%
\else
$^{12}$CO(1-0)%
\fi
}


or

\DeclareRobustCommand{\egregb}{%
\ifmmode
^{12}\text{CO(1-0)}%
\else
$^{12}$CO(1-0)%
\fi
}


and proposed I test things out in an array environment to see what happens.

$\begin{array}{c} \testa \end{array}$


Sure enough, \testa results in the following warning:

! Missing $inserted. <inserted text>$
l.42   \testa

?


whereas the two command \egrega and \egregb work as expected.

I wasn't happy with just this. My understanding of robustness is quite shacky. And, while I've read various posts such as What is the difference between Fragile and Robust commands?, I still felt a bit in the dark.

So, I tried a different approach. I tried writing

$\begin{array}{c} \ifmmode{Math}\else{NOT MATH}\fi \end{array}$


Really, I don't why I did this. I expected to the same error as with the faulty version of the command. But instead I didn't get an error at all. Instead, I got the following unexpected and erroneous result:

Clearly something is going very wrong here, and not in any way I anticipated. If instead I write

$\begin{array}{c} \relax\ifmmode{Math}\else{NOT MATH}\fi \end{array}$


or precede the \ifmmode by anything else to be processed, all seems to go well.

What am I failing to understand here?