JavaScript
Topperworld.in
Performance & Debugging
❖ Performance
JavaScript is an essential part of almost every web app and web-based
software.
JavaScript’s client-side scripting capabilities can make applications more
dynamic and interactive, but it also increases the chance of inefficiencies
in code. Thus, poorly written JavaScript can make it difficult to ensure a
consistent and healthy experience for all users.
Guide below will enlighten you about the causes of JavaScript
performance issues and provide some of the best practices for
optimizing JavaScript code.
➢ Use fast DOM traversal with document.getElementById().
• Given the availability of jQuery, it is much easier to produce highly
specific selectors based on a combination of tag names, classes, and
CSS3.
• You need to be aware that this approach involves several iterations while
jQuery loops through each of DOM elements and tries to find a match.
• You can improve DOM traversal speeds by picking a specific element by
ID.
©Topperworld
JavaScript
// jQuery will need to iterate until it finds the right element
let button = jQuery('body div.dialog > div.close-button:nth-
child(4)')[0];
The above code makes use of JQuery to manipulate the DOM which is not
the best option as instead of doing it this way we can make use of the
getElementById method which the document object provides us.
// A far more optimized way is to use
document.getElementById.
let button = document.getElementById('dialog-close-button');
➢ Delay JavaScript Loading
• Where we load our style sheets and JavaScript files can have an effect
on the perceived speed of a page if the user can see some content even
before the JavaScript takes in it’s a much better experience when a
browser encounters a script tag it stops what it’s doing completely to
download and run the script if we put our scripts at the top of the page
that means it’s downloading our JavaScript files first and then later
getting down to parse our HTML body this means while our scripts are
downloading there is no content for the user to see now if we put our
scripts at the bottom of the page instead by the time, our script starts
loading there’s at least some content on the page making the page seem
to have loaded faster.
• An alternative is to use defer in the script tag.
©Topperworld
JavaScript
• The defer attribute specifies that the script should be executed after the
page has finished parsing, but it only works for external scripts.
Example:
// placing script at the end:
<html>
<head>
<title>My Page</title>
</head>
<body>
<div id="user-greeting">Welcome back,
user</div>
<script type="text/javascript" src="my-
script.js"></script>
</body>
</html>
// using defer:
<script type="text/javascript" src="path/to/script2.js"
defer></script>
➢ Use ‘switch’ instead of lengthy ‘if-then-else’ statements.
• When your code base gets bigger a switch statement is usually more
efficient than a set of nested ifs.
©Topperworld
JavaScript
• This is because ‘switch’ statements can be optimized more easily during
compilation.
➢ Get rid of unnecessary loops and calls made inside loops.
• Array push() pop() and shift() instructions have minimal processing
overhead due to being language constructs closely related to their low-
level assembly language counterparts.
Example:
// push() method
let Animals = ["Tiger", "Giraffe", "Horse", "Deer"];
Animals.push("Zebra");
console.log(Animals);
Output:
➢ Minimize your code as much as you can
• Bundling your application’s components into *.js files and passing them
through a JavaScript minification tool will make your code cleaner.
• There are tons of code minification tools that are available for free.
©Topperworld
JavaScript
➢ Use the local scope (‘this’)
• This is particularly useful for writing asynchronous code using callbacks,
however, it also improves performance because you are not relying on
global or closure variables held further up the scope chain.
• You can get the most out of the scope variable (this) by rewiring it using
the special call() and apply() methods that are built into each function.
❖ Debugging in JavaScript
It is common to have errors while writing codes and the errors can be
due to syntax or logic.
These errors create a lot of ambiguity in the logic and understanding of
both users and programmers.
There can also be errors in the code which can remain invisible to the
programmer’s eye and can create havoc.
To identify these errors we need Debuggers that can go through the
entire code or program, identify the errors and also fix them.
➢ Using debugger keyword
• The debugger keyword is used in the code to force stop the execution of
the code at a breaking point and calls the debugging function.
• The debugger function is executed if any debugging is needed at all else
no action is performed.
©Topperworld
JavaScript
Example: Let’s see the JavaScript program on debugging:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Debugging in Javascript</title>
</head>
<body>
<h4>
Debugging demonstrations using Debugger keyword
</h4>
The solution of 20 * 5 is:
<p id="test"></p>
<p>
If the debugger is turned on the code stops
execution at the start of the debugger
</p>
<script>
const x = 20;
const y = 5;
const z = x * y;
debugger;
document.getElementById("test").innerHTML = z;
</script>
</body>
</html>
©Topperworld
JavaScript
Output:
✓ Previously implementing debuggers was tough but with time and with
the advent of modern browsers, various built-in debuggers came into
implementation.
✓ As previously mentioned the setting up of breakpoints breaks the line of
code and flows the control to another area from where it is called.
✓ This can be done in the debugging window of the browser.
✓ Also setting up of breakpoints in javascript acts similar to the
breakpoints in Java where the execution of the code stops and
examination of the values is performed by the browser.
✓ One can resume the flow control after the examination is done.
✓ The debugging can be turned on or off depending upon the user’s
convenience.
✓ This all can be done through the “Console” of the debugger menu.
©Topperworld
JavaScript
➢ Use of console.log() method
• There is another way in which the JS values can be displayed in the
debugger window.
➢ Setting Break Points
• The console.log() is a good way to debug errors but setting breakpoints
is a faster, more efficient, and better method.
• In this method, Breakpoints are set in code which stops the execution of
code at that point so that the values of variables can be examined at that
time.
Here are some advantages of using Breakpoints over the console.log() method:
✓ In the console.log() method user has to understand the code and
manually put console.log() at points in the code. But in the breakpoints
method, we can set breakpoints through the Developer tool anywhere
in the code without even knowing it.
✓ In the console.log() method we have to manually print values of different
variables but at a certain breakpoint, all the values of all variables are
displayed automatically in the Developers tool. Enter the Developers
tool section by pressing F12 key and go to sources. In the source section,
select a javascript file and set breakpoints by either selecting from the
provided list like DOM breakpoints or Event listener breakpoints which
stop the execution of code whenever an event occurs OR set a
breakpoint by simply clicking the line number shown in the code. In the
©Topperworld
JavaScript
following image, a breakpoint is set at line 23. (The code used is the same
as the above example)
❖ JavaScript Errors Throw and Try to Catch
• When executing JavaScript code, errors will definitely occur.
• These errors can occur due to a fault from the programmer’s side or the
input is wrong or even if there is a problem with the logic of the program.
But all errors can be solved and to do so we use five statements that will now
be explained.
✓ The try statement lets you test a block of code to check for errors.
✓ The catch statement lets you handle the error if any are present.
✓ The throw statement lets you make your own errors.
©Topperworld
JavaScript
✓ The finally statement lets you execute code after try and catch.
The finally block runs regardless of the result of the try-catch block.
Example 1:
try {
dadalert("Welcome Fellow ");
}
catch (err) {
console.log(err);
}
Output: In the above code, we make use of ‘dadalert’ which is not a reserved
keyword and is neither defined hence we get the error.
©Topperworld
JavaScript
Example 2:
function Func() {
let a = 10;
try {
console.log("Value of variable a is : " + a);
}
catch (e) {
console.log("Error: " + e.description);
}
}
Func();
Output: In the above code, our catch block will not run as there’s no error in
the above code and hence we get the output ‘Value of variable a is: 10’.
©Topperworld
JavaScript
➢ Try and Catch Block
• The try statement allows you to check whether a specific block of code
contains an error or not.
• The catch statement allows you to display the error if any are found in
the try block.
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
➢ Javascript Throws Block The throw Statement
• When any error occurs, JavaScript will stop and generate an error
message.
• The throw statement lets you create your own custom error.
• Technically you can throw your custom exception (throw an error).
• The exception can be a JavaScript Number, String, Boolean, or Object.
• By using throw together with try and catch, you can easily control the
program flow and generate custom error messages.
©Topperworld
JavaScript
Example:
try {
throw new Error('Yeah... Sorry');
}
catch (e) {
console.log(e);
}
Output:
➢ The finally Block
The finally Statement runs unconditionally after the execution of the
try/catch block.
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch
result.
}
©Topperworld
JavaScript
Example:
try {
console.log('try');
} catch (e) {
console.log('catch');
} finally {
console.log('finally');
}
Output:
©Topperworld