Friday, 25 December 2015

JavaScript Myths, Malpractices and Best Practices

So why is JavaScript so frowned upon in the first place? Here are a few reasons that possibly contributed to the bad reputation:

  1. The Name: JavaScript has nothing to do with Java. Yes. It was intentionally mis-positioned by its creators to get around some business dealings. Hope that settles the confusion.
  2. Object Oriented and Functional Language in One: Functions are first class objects in JavaScript. That means functions can have properties and can be used to create objects. JavaScript is a class-free object oriented language. If fact, its quite a powerful Object Oriented Language at that.
  3. Prototypal Inheritance: In languages like C++, C# or Java – classes inherit from other classes. That’s Classical Inheritance. In JavaScript, there are no classes. So objects inherit directly from other objects. You can modify an object’s prototype after its creation and affect all objects using that prototype to receive that modification. This is quite like Extension methods in C# – which was introduced much later, in C# 3.0.
  4. Lambdas: Simply said, Lambdas are function pointers. JavaScript handles lambdas so easily that it doesn’t even feel like a big deal. In C# 3.0, Lambda Expressions were introduced and anyone who knew how to use them right felt they had just mastered rocket science.
  5. Anonymous Functions & Types: Anonymous functions and types are a rage in JavaScript. C# introduced this feature too in its 3.0 version to enable support for LINQ syntax.
  6. Inline Functions & Closures: Something that would be frowned upon in other systems, you will see inline and anonymous functions used everywhere in the best implemented JavaScript code. Not just because its easy but to tap into the magical yet mostly unknown feature of JavaScript called Closures.
  7. Bad Tutorials, Programmers and Implementations: Even today, there are tons or tutorials, classes and books teaching JavaScript all wrong. This was probably because of poor JavaScript implementations in older browsers causing developer fatigue and hence giving a poor reputation to the language itself.
  8. JavaScript and the Web: JavaScript is the only language that can be used to provide client side interactivity in a normal HTML webpage. Hence it is typecast into being a Web Toy but it really is a full programming language. In fact, there are other software applications that have JavaScript support in them. Like Windows Apps, iOS apps, PDF Readers and the big one – server side JavaScript using Node.js.
  9. Security Concerns: People dread the fact that someone else’s code can get downloaded into their computers and wreak havoc in their lives. JavaScript by itself cannot do harm to your computer. The browser restrictions on it are good enough to keep you safe. The problem however is extensions you install on your browser like Adobe Flash, Microsoft Silverlight, Java and more. What most people need to block are those extensions using Flashblock & AdBlock add-ons and enable them only on sites they trust.
  10. Loose Typing: You don’t have much of a choice on this one. Strong Typing is beneficial but JavaScript’s loose typing has some benefits that make it very friendly for rapidly building & maintaining applications that require constant change and updates. Similar to the move most applications are making to NoSQL (Big Data) databases from traditional Structured Relational Database Models.
  11. Linkage via Globals: I do agree this is fairly nasty but there is really no other way. JavaScript is delivered as text/source code to the browser and hence has no Linker to link the various components and modules. All JavaScript code executes in the same namespace on a webpage. The linkage is done via global variables such as the window object. This is quite problematic and a developer should work around it and I will discuss this specifically.

How do I do JavaScript Right? Are there some best practices?

JavaScript does not enforce many standards itself and hence beginners could get it very wrong if they started learning it the wrong way. Here are a few tips to get you headed in the right direction:
  • Unobtrusive JavaScript:
The days are long gone when you did something like this and could still keep your job:
This is called Obtrusive JavaScript and is the most taboo thing you could do today. Unfortunately, some server side systems (like ASP.NET) still emit code that looks much like this. What you should always do is separate your JavaScript code from your Markup HTML and use Event Listeners to bind event handlers to events on elements like this:
Doing something like this is also a bad idea:
This means that if your requirements change regarding your border styling, you will need to update this code. Ideally, you should use CSS classes to achieve the desired effect and manipulate the className property alone. Modern browsers even support a classList but be careful while using them and provide a means for Graceful Degradation.
  • Understanding Global Variables:
Because everything in JavaScript is an object (including primitive types), many don’t understand the scope of variables and functions when they create them. When you create a function or a variable outside a function, you are creating it in the Global scope – referred to by the window object. This is also the case when you create variables inside a function without using a “var” declaration preceding them.
  • Namespacing your code:
A very important thing to remember when writing your code is to not clutter the Global namespace with your function names and variables. You can namespace your code effectively using a Module Design Pattern or Self Executing Anonymous Function (Immediately Invoked Function Expression). Example below:
This style of coding limits the clutter of the global namespace to just one variable (module), provides a private namespace for all your functions and variables exposing only those that need to be exposed and also allows you to import variables using your preferred variable name without worrying about global naming conventions. jQuery plugin developers know this one very well.
  • Object Oriented Programming:
One can forget that JavaScript is object oriented and start writing just functions that call other functions like in a procedural language. However, using objects for managing state and data of your applications in the browser is a pretty amazing way to build rich client applications. Frameworks like Knockout, Backbone, Angular etc. do help in this direction but having a good understanding of how to do Object Oriented Programming is a very important skill.
  • Loading Scripts at the Bottom:
Enough has been said about this everywhere but I have to reiterate it. Some may argue that modern browsers can handle this and hence it doesn’t matter anymore. Also there is the confusion with the “defer” and “async” attributes on the script tag. I think i’ll letGrowingWithTheWeb explain it better. Ground rule for now – put the <script> just before the closing body tag, not in the <head> tag as most beginner tutorials tell you.
  • Waiting for Window Load / DOM Ready:
This isn’t just a best practice, its more like – do it or your code won’t work. When you start doing unobtrusive JavaScript, it becomes a responsibility to wait for the window load event to fire or the DOM to be ready. DOM ready isn’t an event and the easiest way to listen to it is by using jQuery. window.onload fires when all resources necessary to render the page are ready but that might be too late for some scripts to kick in, like say a Slideshow. In that case, the DOM ready might be a more appropriate which occurs as soon as the DOM tree is ready.
  • Don’t Use Alerts
If you’ve not experienced the pain of an alert box on a page, please try this. This applies to to confirm and prompt boxes as well. They are modal dialogs, block the browser from performing any other function and in some cases, affects other tabs too. If you expect even a least bit of visitor loyalty, don’t use alerts. There are sufficient DOM based alternatives to alert the user without blocking the browser and all other tabs. Try the jQuery UI Dialog widget or the Bootstrap Modal component.
  • Use JSON:
JSON is native to JavaScript. So effectively using JSON to maintain state and data is actually using Object Oriented JavaScript. Given the advent of server side frameworks like the ASP.NET Web API, building sleek RESTful apps that manage UI state in the browser by just transferring JSON data between client and server using Ajax calls is really the way of the future web apps. Plus libraries like Angular or Knockout use this to their advantage to perform 2-way data binding between DOM elements and JSON data. Everything is falling in place now.
  • Using those F12 Tools:
Using a loose typed langauge with no compiler to pick up syntax errors and typos, bugs may be hard to find. Not having the power of the Console in the F12 developer tools of the browser only weakens a JavaScript developer. If something doesn’t work, the F12 Console is your best friend. Plus being able to step though your code using a debugger is a real power to see the execution of your code plus learn more about the language and the environment.
  • Tap into Event Bubbling:
Event’s bubble up. Its not a bug but its a requirement by browsers to support event bubbling. What that means is if an event occurs on a specific element, it fires first on the element itself and then bubbles up to its parent and fires on that element next, then onto its parent and so on. That is very useful in building applications where you have multiple similar elements that need to respond to an event. Seems like a rare requirement? Not so much. You right click on an email in Gmail and a context menu of options appears. There’s no event handler listening to events on every single email on that page, its a common handler written on the container of those email elements. You then use the target property of the event object passed into your event listener to find the original element on which the event occurred and take necessary action accordingly.
  • Use JSHint or JSLint:
JSLint and JSHint are essential tools to check code quality, pick out bugs and potential problems in your coding conventions. They are configurable and can be added as plugins for your text editors/ IDEs or as downloadable programs to run when you build your project.
  • Compress & Bundle:
ASP.NET MVC 4 came with the WebOptimization package which allowed for you to configure JavaScript and CSS Bundles and have them all get minified and bundled into single files optimizing your page load times. But even otherwise, you should always minify and bundle your JavaScript and CSS files to optimize the page size as well as load time by minimizing HTTP requests.
  • Don’t forget Accessibility
Last but not the least, what happens when JavaScript is disabled? If you believe that a user comes across your website with JavaScript always on, think again. Accessibility is a big deal. Screen readers cannot work with JavaScript. People with limitations will have a very difficult time using your website if you did not provide a version that works without JavaScript. In fact, some applications are required by law to provide accessibility (Read Section 508 or WCAG). You could look into Accessibility or ARIA for more info.

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...