House3272 House3272 - 1 year ago 82
Javascript Question

Correct or standard way to write non-'terminating' code?

Apologies, but I'm not sure what the term for what I'm asking is.

What I'm referring to is when a bit of code fails and prevents any further code from executing.

When chucks of code are not dependent on each other, there's no reason the failure of one chunk should stop the rest right?


const div1 = document.querySelector('#alphaDiv'); = 'red';

const div2 = document.querySelector('#bravoDiv'); = 'flex';

if for some reason there's an error with the
code, the execution would stop there and
's code would never run.

To address this, I've always used a
try catch
to segment non-interdependent code/function calls.

Is that generally how it's done? Or is there a standard best practice for this sort of contingency?

Also, is there a generic term for what I'm referring to?


I'm specifically asking for client side, when things like this occur.

It just seems like a losing battle to discover and handle every tiny quirk of every browser.

Answer Source

You need to balance the probability that something fails.

For example, you don't need try...catch if your document.querySelector don't throw.

However, document.querySelector will throw if the browser does not recognize #alphaDiv as a valid selector. But the probability of encountering a browser which doesn't support ID selectors is probably negligible. As an alternative you can consider document.getElementById. It will be faster, and should never throw.

Excluding querySelector errors, you can check that every value on which you attempt to retrieve a property or which you attempt to call really exists. Something like

if (document.querySelector) {
  // Let's assume the browser can parse CSS ID selectors
  const div1 = document.querySelector('#alphaDiv');
  if (div1 && { = 'red';
  const div2 = document.querySelector('#bravoDiv');
  if (div2 && { = 'flex';

There are also some assumptions in there, e.g. that if document.querySelector is truthy, then it has the proper value.

But even when coding defensively like this, there can still be problems. If I recall correctly, old versions of IE threw an error when assigning unsupported CSS values in style.

So you must decide, if you want your code to be completely safe, probably it's better to use try...catch. But it's ugly and may make the code slower on some engines. And usually it's not worth it.

You also mention setTimeout. That can work, but has remember it's asynchronous. Depending on what you want to do, this can be a problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download