Article 63HCN CodeSOD: Undefined Variable

CodeSOD: Undefined Variable

by
Remy Porter
from The Daily WTF on (#63HCN)

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 about this pointless conditional, throwing up a warning that the ConditionIsAlwaysConst: it can't be anything but true. But even with the tool pointing them in the right direction, they couldn't think through why that was the case, so they just turned off the warning.

While this isn't a serious bug in the code, this does put in mind the person who is annoyed that their Carbon Monoxide detector won't stop going off, so they unplug it. It's easy to pass linting if you disable any warning that comes up.

proget-icon.png [Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments