How JavaScript Try and Catch, Cross Browser Testing, Caching are Works?

Mahabub Sunny
6 min readMay 6, 2021

Today we are disusing Testing, Performance, Errors, Caching. How it actually works? Every Programmer needs to know this. Error is a common thing every Programmer face, no matter how great we are at programming, sometimes our scripts have errors. They may occur because of our mistakes, unexpected user input, an erroneous server response, and for a thousand other reasons.

Usually, a script “dies” (immediately stops) in case of an error, printing it to console. But there’s a syntax construct try…catch that allows us to “catch” errors so the script can, instead of dying, do something more reasonable.

The “try … catch” syntax!

Try and catch has two main blocks one is try and another one is catch.

try {// code…} catch (err) { // error handling}

It works like this:

  1. First, the code in try {...} is executed.
  2. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch.
  3. If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err). The err variable (we can use any name for it) will contain an error object with details about what happened.

So, an error inside the try {…} block does not kill the script — we have a chance to handle it in catch.

Let’s look at some examples.

An errorless example: shows alert (1) and (2):

try {
alert(‘Start of try runs’);
// (1) <--
// …no errors here alert(‘End of try runs’);
// (2) <--
} catch (err) {
alert(‘Catch is ignored, because there are no errors’);
// (3)
}

Do You know try…catch only works for runtime errors?

A program during execution is called runtime errors. The main purpose of try…catch to work, the code must be runnable.


try {
{{{{{
} catch (err) {
alert(“Error has occured”);
}

try…catch works synchronously

If a programmer used the set timeout method, then try catch won’t catch it.


try {
setTimeout(function() {
myVariable
}, 1100);
} catch (err) {
alert( “didn’t work” );
}

But, if you want to catch an exception inside a function try…catch must be used.


setTimeout(function() {
try {
myVariable;
} catch {
alert( “Error” );
}
}, 1000);

Error Object

When an error occurs, JavaScript generates an object that are passed as an argument to catch.


try {
// code
} catch (err) { //error object
// code
}

“catch” binding

If we don’t need any details information about error, catch may ignore it.


try {
// code
} catch { // without err
// code
}

Using “try…catch”

Let’s go to a real-life example, JSON. We mainly used to get the decoded data by using JSON parsing. A simple example of JSON is:


json = ‘{“name”:”Mahmudur”, “age”: 23, “occupation”: “Web Developer”}’;

If the JSON is not correct, it generates an error.


let json = “{ wrong json }”;
try {
let user = JSON.parse(json);
alert( user.age ); // doesn’t work
} catch (err) {
alert( err.name );
alert( err.message );
}

Own errors

Sometimes, you see that JSON is syntactically correct but you don’t have an occupation property. See this.


let json = ‘{ “age”: 23 }’;
try {
let user = JSON.parse(json); // ← no errors
alert( user.occupation );
} catch (err) {
alert( “no execution” );
}

instance of operator

We can check the type of error by using the instance of an operator.


try {
varA = { /*…*/ };
} catch (err) {
if (err instanceof ReferenceError) {
alert(‘Error has occured’);
}
}

Reference error mainly used for an undefined variable.

try…catch…finally

finally, the statement used to execute the code after try and catch. The code is:


try {
// code
} catch (err) {
// code
} finally {
// code
}

Cross Browser Testing

Cross-browser testing is the practice of making sure that the websites and web apps you create work across an acceptable number of web browsers. As a web developer, it is your responsibility to make sure that not only do your projects work, but they work for all your users, no matter what browser, device, or additional assistive tools they are using. You need to think about:

  • Different browsers are other than the one or two that you use regularly on your devices, including slightly older browsers that some people might still be using, which don’t support all the latest, shiniest CSS and JavaScript features.
  • Different devices with different capabilities, from the latest greatest tablets and smartphones, through smart TVs, right down to cheap tablets and even older feature phones that may run browsers with limited capabilities.
  • People with disabilities, who use the Web with the aid of assistive technologies like screen readers, or don’t use a mouse (some people use only the keyboard).

Remember that you are not your users — just because your site works on your MacBook Pro or high-end Galaxy Nexus, doesn’t mean it will work for all your users — there’s a whole lot of testing to be done!

We should explain a few bits of terminology here. To start with, when we talk about sites “working cross-browser”, we are really saying that they should provide an acceptable user experience across different browsers. It is potentially OK for a site to not deliver the exact same experience on all browsers, as long as the core functionality is accessible in some way. On modern browsers, you might get something animated, 3D, and shiny, whereas on older browsers you might just get a flat graphic representing the same information. As long as the site owner is happy with this, then you have done your job.

On the other hand, it is not OK for a site to work fine for sighted users, but be completely inaccessible for visually impaired users because their screen reader application can’t read any of the information stored on it.

Second, when we say “across an acceptable number of web browsers”, we don’t mean 100% of the browsers in the world — this is just about impossible. You can make some informed calls as to what browsers and devices your users will be using (as we’ll discuss in the second article in the series — see Gotta test ’em all?), but you can’t guarantee everything. As a web developer, you need to agree on a range of browsers and devices that the code definitely needs to work on with the site owner, but beyond that, you need to code defensively to give other browsers the best chance possible of being able to use your content. This is one of the great challenges of web development.

Caching

In the online space, many techniques are collectively referred to as “caching” due to their ability to mirror this functionality. In the most simple terms, caching is a general computer concept that provides efficiency through data availability. The mechanism by which this is accomplished is through the storage of commonly accessed data in several places, and then serving that data to requesters from the common data store. This is opposed to generating new content each time it is requested.

By providing commonly requested data to users who often request that data when calling the same functions, you can avoid a lot of extra data generation, optimize the request workflow, reduce time to delivery, and remove congestion on your API input/output path by saving vital processing and networking resources.

By storing this data, efficiency is improved. When a requester makes a request for this data, the API prioritizes stored versions, wherever that cache might be, over data generation, allowing for your delivery while freeing up otherwise occupied sources. This can be used for computed data, but it’s also extremely helpful for certain types of static information — for instance, if the requester is asking for the location of an unmoving file, a directory, or even a version number, this information should be cached ahead of time and used for a quick, efficient response.

--

--