CodeSOD: Undefined Variable

This post was originally published on this site

The Daily WTF

Robert H was trawling through the JavaScript front-end for his team’s ASP.NET MVC application. The goal was to prepare for a complete rewrite of the front-end, because, well, it had problems and wasn’t reliable or maintainable.

As an example, Robert sends this:

function orderSearch() { // ReSharper disable once ConditionIsAlwaysConst if (typeof loadingText === “undefined”) { var loadingText = window.Resources.Messages.Loading; } … }

This code is a wonderful example of (ab)using the var keyword, instead of the newer let keyword for defining variables. var declared variables automatically get “hoisted”- they’re always scoped to the function.

Which highlights why this code is pointless: of course loadingText is undefined, we literally define it on the next line. Given the way the variable is used, this entire block could be redefined as:

const loadingText = window.Resources.Messages.Loading;

But the real gem in this code is the ReSharper hint. Their linting tool complained

To read the full article click on the 'post' link at the top.