# Problem with newcommand and the optional argument

You want to test whether the optional argument is empty or not:

\documentclass[a4paper]{article}

\newcommand{\stuffing}[2][]{%
W_{\mathtt{#2}}%
\if\relax\detokenize{#1}\relax
\else
^{^{[#1]}}%
\fi
}

\begin{document}
what I want: $W_\mathtt{a}$ and $\stuffing[5]{a}$

but what I get: $\stuffing{a}$ and $\stuffing[5]{a}$
\end{document}


I removed \ensuremath because that's math and so it should be properly segregated and you gain very little in not using $...$ a few times.

With xparse you can use the o argument type:

\documentclass[a4paper]{article}
\usepackage{xparse}

\NewDocumentCommand{\stuffing}{om}{%
W_{\mathtt{#2}}%
\IfValueT{#1}{^{^{[#1]}}}%
}

\begin{document}
what I want: $W_\mathtt{a}$ and $\stuffing[5]{a}$

but what I get: $\stuffing{a}$ and $\stuffing[5]{a}$
\end{document}


With etoolbox:

\documentclass[a4paper]{letter}
\usepackage{etoolbox}
\newcommand{\stuffing}[2][]{\ensuremath{W_{\mathtt{#2}}\ifblank{#1}{}{^{^{\left[#1\right]}}}}}

\begin{document}

what I want: $W_\mathtt{a}$ and \stuffing[5]{a}

and what I get: \stuffing{a} and \stuffing[5]{a}

\end{document}