Professional JavaScript 2022: New Frontiers & Strict Standards - ByteScout
  • Home
  • /
  • Blog
  • /
  • Professional JavaScript 2022: New Frontiers & Strict Standards

Professional JavaScript 2022: New Frontiers & Strict Standards

New standard methods of JavaScript development are at hand and demand our attention because of their potential for voluminous deployment across millions of important websites today. The new ECMAScript 2017 defines world-changing optimizations that we can deploy to greatly improve performance. JavaScript’s extensibility recently appears boundless. Frameworks such as AngularJS have reshaped JavaScript development with truly dynamic SPAs. Libraries like JQuery are now so prolific and commonly used that JQuery appears alongside JavaScript as a skill requirement in job descriptions. And the environment Node.js enables JavaScript to escape the browser and run on the server-side! These are but a few of the predominant new frontiers that the professional JavaScript developer must master to reach full-stack. In this ByteScout review, we will scan across the exciting new world of JS development in search of the future expectations that pro-JS coders can expect to face.

  1. ECMAScript 2017 Demands Your Attention
  2. A New Angle on Frameworks
  3. Know Your Node!
  4. Professional Best Practice Coding
  5. Tips For Debugging JavaScript
  6. A Brief Word About Tools
  7. The Front and Back

Along the way, we will also explore “best practices” in coding JavaScript, including tips for writing highly readable code. The new Async and Await functions described by ECMAScript 2017 go a long way toward making our code easier to read and update. Maintainable code means not only readable but also sensible, orderly code which another coder can also maintain without a decipherment headache. And we will also look at popular debugging – linting – and testing methods to boot. These methods although not so exciting are equally important to the true professional. Experience with these will surely impress prospective project managers. So let’s begin by diving right into the optimizations!

ECMAScript 2017 Demands Your Attention

The professional JavaScript developer is obliged to achieve mastery of an astonishing set of new and emerging tools, APIs, libraries, environments, and frameworks. Perhaps equally daunting is the challenge to optimize new code and update existing libraries in accordance with the best new feature additions to the core of JavaScript itself. Let’s break off a piece of this challenge and learn how to use a piece of the new ECMAScript 2017 spec to optimize page loads. Who knows better than the browser architects themselves how best to load pages!

Today’s top pro JavaScript developer is capable of optimizing web pages using the latest feature updates to JavaScript including the new ECMAScript 2017 Async and Await functions. Optimizing web pages provides a highly responsive site for visitors and efficiently reduces the load on all your servers, as well as reduces demand on Internet connection bandwidth. This is especially relevant for sites with high volume and frequent traffic spikes. Perhaps surprisingly, optimized page loads will dramatically improve performance for site visitors with fast connections!

Let’s see exactly where Async functions fit into an optimized page load strategy. In general, write JavaScript to be compatible with both Async and Defer. Use async as often as possible. This is especially valuable when there are multiple script tags. The point is to asynchronously load scripts that are crucial to the visitor’s experience. Before we look at the new method, let’s look at an old familiar way of lazy loading a file to get a basis of comparison.

We need to dissect a site to determine which elements need lazy loading, but photos usually account for 50% of the average site’s size. With lazy loading of images in mind, we will optimize the initial download time of a page while continuing to load all the required images automatically. To try out the script below, modify your images to lazy load so that the “src” property points to the blank loading spinner. Then add a custom attribute like data1-src below to store a reference to the actual image to be lazy-loaded, like this:

// first the images:

img src="data:image/gif;base64,R0l7" data1-src="image.gif"
img src="spinner.gif" data1-src="image2.gif"

// and the lazy load:

window.addEventListener('load', function1(){
var allimages1= document.getElementsByTagName('img');
for (var i=0; i<allimages1.length; i++) {
if (allimages1[i].getAttribute('data1-src')) {
allimages1[i].setAttribute('src', allimages1[i].getAttribute('data1-src'));
}
}
}, false)

If you are familiar with asynchronous page loading the old way, then you may have seen something like this before, but clearly, the lazy load code is far from transparent and not easy to read. Now, compare the above method of lazy loading images with the new ECMAScript 2017 asynchronous function. In the following script, we will load a JSON file using the Async function. In this example, Async automatically creates and returns a Promise, like this:
// Async automatically creates and returns a Promise…

async function1 getJSONAsync(){
    let json1 = await myLib.get('https://bytescout.com/myexample.json');
    return json1;
}

Now, the results of the GET are available in the parsed json1 variable. This is returned as with the asynchronous function (order preserved). Although the functionality is similar, the clarity of syntax and the brevity are remarkable. Here is a dramatic improvement to asynchronous coding in JavaScript which will visibly affect the way developers write code tending to a concise and highly readable form. For a more thorough look at new enhancements to JavaScript 2017, see our top 10 New Features of ECMAScript article here.

A New Angle on Frameworks

JavaScript in recent years has been stretched far beyond its original scope first by AJAX, which envisioned binding variables to HTML elements and the first dynamic page updates, and more recently by AngularJS, which takes on the challenge of creating full-function Single Page Applications. SPAs are web pages that load-independent components asynchronously and update the page dynamically rather than loading other pages. This ultimately creates a user experience resembling a desktop application. Indeed it has become the defacto standard for high-performance web pages, and SPAs show the highest optimization potential for page load order and “best practices” development toward enhanced user experience. Let’s have a look at how AngularJS transforms the way web pages are built.

AngularJS introduces the “model-view-controller” which is a sophisticated way of designing the interaction between the user and page elements. The key component of MVC is Data-binding. This is an automatic refresh that occurs in which the view updates when the model changes and the model updates whenever the view changes. It is a dynamic enhancement that relieves us of direct manipulation of the DOM. Old school professional advice claims JavaScript should be static. In view of what we have seen with Angular and Node specifically set up to provide dynamic content, JavaScript is clearly trending toward dynamic behavior.

Within MVC, controllers contain the coded behavior beneath DOM elements. AngularJS objects are plain JavaScript objects. With AngularJS we can represent behaviors in clean, readable scripts without the usual tedium of updating the DOM or manually watching for model changes. Here again is the emphasis on creating readable and accessible code, and it is coming from the architects of the framework itself! Let’s look at a simple example that shows the MVC in action in an AngularJS script:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Type your favorite color in the box:</p>
<p>Color : <input type="text" ng-model="name" placeholder="Enter color here"></p>
<h1>Favorite color {{name}}</h1>
</div>
</body>
</html>

In the following example, AngularJS binds the Name variable to the HTML element. When you type something in the box everything updates. The model, view, and controller all update, and the page updates dynamically. Notice that the page element updates each time you time a letter!
Because we are here to explore the future of pro JS development, it is important to mention that AngularJS recently evolved to Angular2+ and this is a perfect segway to point out that the popular JS frameworks today share a lot of common features. Choice of which framework you choose to learn may boil down to which one is connected to the most job openings or which one has the most GitHub stars. React is a similar framework with its own specialized libraries for doing common tasks like developing UIs.

Know Your Node!

Node.js is another JavaScript framework that is indispensable to the pro-JS developer. This framework enables developers to write JavaScript to be run on the server-side and can run on all the most popular platforms including Windows, Linux, Unix, Mac, and OS X. The primary theme that all of our JS developer tools share in common ranging into the future is asynchronous coding, and Node.js is no exception. Before looking at a sample script, let’s compare how Node.js and PHP handle a file request:

PHP processes a file request in this order:

  1. Send the request to the file system.
  2. Wait while the file system opens/reads the file.
  3. Return the content to the client.
  4. Ready for the next request.

Node.js processes a file request in this order:

  1. Send the request to the file system.
  2. Ready for the next request.
  3. Whenever the file system opens/reads a file, return the content to the client.

This asynchronous functionality means that Node.js can deliver files to a user-experience optimized page without bogging down in sequences. Node.js listens to a port on the server, and a typical Node.js event fires when someone tries to access the port. Although you need to install Node.js on your computer to run the following script, you can see what is happening just by reading it:

// Node.js’s hello world!
var http = require('http');

http.createServer(function1 (req, res) {
	 res.writeHead(200, {'Content-Type': 'text/html'});
	 res.end('Hello World!');
}).listen(8080); 

Professional Best Practice Coding

Professional coding involves collaboration, which in turn requires clear communication of goals. One frustrating source of miscommunication among coders is inadequately or incorrectly commented code. There is standard code commenting styles such as JSDoc, and following a clear plan of commenting is important to your future comprehension of the code you write today. Other coders tasked with updating your code in the future will also depend on the descriptions you write into your code in the current context. Following a consistent plan of highlighting and consistently indenting your code is also important to readability, and is as easily achieved as piping your code through a code beautifier. As we have seen, coding to lazy load files is by no means clear and readable. Asynchronous flows and their intended behavior deserve more comment lines in the code to make it maintainable. Identify complex sections of your code which are likely to appear cryptic only a few months in the future, and target these sections for descriptive comment lines.

Tips For Debugging JavaScript

The best debugging is preventative debugging. Using clear and established standard methods of coding reduces the likelihood of introducing errors and also makes it easier to find bugs later. A great example of this is the concept of coding to interfaces rather than implementations. This is the proper implementation of closures in JavaScript. As with a lot of common JS keywords, it is likely that you have used this concept in coding even if you did not know what it was called. Once again we are talking about reusable code.

As with encapsulation in general oop, closures maintain the privacy of data objects by limiting the lexical scope of the current object to the outer function’s scope (plus its own variables and global variables). In the snippet below, the inner function has access to the scope variables and parameters of the outer function:

function showNames (firstName, lastName) {

var namesIntro = "The name is ";

function makeFullNames () {
        
return namesIntro + firstName + " " + lastName;
    
}

return makeFullNames ();

}


showNames ("Carsten", "Dedreu");

As JavaScript coding standards evolve, we can see a lot of ideal functionality emerging where these theoretical coding practices or “best practices” work together toward multiple goals. In this case, we have reusable code and data privacy built into a concept of preventative debugging!

Techniques that tend to avoid bugs preventatively involve measures such as developing the habit of looking through libraries for functionality before spontaneously writing code from scratch. Very often the code you need already exists in one library or a combination. Using pre-existing code thoroughly avoids the time lost to debugging original code. The perfect starting place is JQuery.

JQuery is the most widely deployed library on the Internet, and it has the purpose of simplifying JavaScript coding. JQuery consolidates thousands of common tasks which would require many lines of code and wraps them nicely into methods that can be called with one line of code. Professional developers actually have no time to waste and efficiency dictates that they exploit this mountain of rich coding resources. JQuery simplifies DOM manipulation and AJAX calls. So let’s have a look at a sample and see how to get started:


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Define JQuery slide effect
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>

<style>
#panel, #flip {
padding: 4px;
text-align: center;
background-color: #e6e2cc;
border: solid 1px #c5c2c3;
}

#panel {
padding: 40px;
display: none;
}
</style>
</head>
<body>

<div id="flip">Click this to slide the panel down.</div>
<div id="panel">Greetings from ByteScout!</div>

</body>
</html>

This code snippet demonstrates the use of one of the myriad JQuery effects methods. The Slidedown method effectively slides an HTML element down to reveal something hidden. The range and variation of such methods are limitless, and there are also plugins to JQuery which extend the library even further. Developing good research habits such as finding pre-existing methods like this rather than writing them yourself will free up a lot of time for more urgent tasks truly requiring our originality.

A Brief Word About Tools

Along the lines of debugging, linting is the best and quickest way to spot syntax errors and style problems in JS code. There are many good pluggable linting tools available with customizable rules, and these run on the command line interface. The wildly popular Gulp for setting up builds is yet another way of streamlining development. Try running a linting tool within a Gulp build to add debugging. Additionally, Dojo abstracts browser objects so that you can use a single API code for all of them at once. To further reduce the impact of variable browser support for newer JS features we can transpile ES6 back to ES5 with freely available tools.

The Front and Back

JavaScript has been extended so far beyond the browser scope that we can now develop back-end data code for database management running JS code through Node.js on servers. There is clearly no end in sight and so as developers, we will eventually be required to choose specializations within JavaScript. This has already happened in several large enterprise development ecosystems, but as we can see in job postings, the specializations involving extensions to JavaScript are arriving from all directions. Stay tuned to ByteScout, where we aim to keep you in the event loop!

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next