Fixing a network 404 error using typeof

Javascript’s typeof operator is an essential debugging tool that many young programmers often miss. Countless times I’ve run into situations where my program wasn’t working because either my variable was unnoticeably coerced or I was just completely unaware of a data type. As mentioned in a previous post – a season programmer should know their data types! Another thing a seasoned programmer ought to know is to prevent themselves from being too arrogant – yes, we need help and using the “typeof” operator is there to the rescue.

I’ve been getting a lot of optimization requests from my consulting clients – and, optimization is such a broad term. It could mean anything, but generally speaking we are talking about site speed. If we narrow that down, well we get a really long list of solutions thanks to Google Page Insights. Even more, Page Insights is powered by Lighthouse and I’ve done my research – Lighthouse Technology is totally legit.

Back to the typeof operator – this solution didn’t arrive so quickly when I was trying to debug a situation where some variable was “undefined”. Yeah, undefined – such a mystical data type. It’s almost up there with “null” and “NaN”. Javascript can be so weird sometimes, you don’t really know what you’re dealing with.

And so some variable was floating around, let’s call this variable “time”. So in a program it could look sometime like this:


if (time) {

 // ... a bunch of code ...
 // ... a bunch of code ...

}

The console was throwing an error and rightfully so – time was undefined. This can be caused by anything but what first comes to mind would be some javascript, framework or library that isn’t utilized on that particular page – happens a lot. Perhaps it’s only utilized on a gallery page, but the library in embedded globally throughout the site.

So how do we get rid of it? Well at first I tried the handy dandy boolean check before the program is run:


if (!time) {
  return;
}

if (time) {

 // ... a bunch of code ...
 // ... a bunch of code ...

}

Well that didn’t work, same result. Let’s try comparing it against the data type in question – yes, “undefined”.


if (time === "undefined") {
  return;
}

if (time) {

 // ... a bunch of code ...
 // ... a bunch of code ...

}

Nope, that didn’t work – so, this is where typeof solves the issue – straight up. This time, we’ll output the variable by logging it.


if (typeof item === 'undefined') {
        return;
}

if (item) {

  console.log(item);
}

So in the code above, we never get to logging the item. We use the return operator to end the program’s execution.