Rules to Better JavaScript and jQuery

​​

Hold on a second! How would you like to view this content?
Just the title! A brief blurb! Gimme everything!
  1. Do you always use semicolons on your JS file?

    For most of the cases, it quite rare to have problems when omitting semicolons, but there are a few scenarios where they are required to prevent syntax errors or resolve code ambiguities.

    To save yourself time and troubles, it's highly recommended that you just place them all the time. More than avoiding you to have some headaches, your code will also look a lot more consistent.

  2. Do you avoid making changes to individual CSS styles using jQuery?

    We all know that jQuery is very powerful and can do a lot of stuff, including style changes. However, this practice is bad.

    Instead of changing the appearance of elements with jQuery, you should use CSS classes. This way you can keep all your CSS in your CSS files, specify different appearances for different classes.

    It's OK to use jQuery to add or remove classes and apply your CSS. For this we can use .addClass() and .removeClass() methods.

  3. Do you avoid relying on Javascript for crucial actions?

    Don't assume JavaScript is always enabled.

    JavaScript should be used to enhance the overall user experience and not as a dependency.

    JavaScript is very useful for improving user-interaction, along with reducing the number of requests made on the server; but it can be disabled - an estimated 2% of web users do not have JavaScript enabled

    Depending on your audience you may choose to disregard this rule, but for mainstream websites it is highly recommended that you don't rely on JavaScript for crucial actions, such as validation or business-logic purposes. Do a server-side validation instead.

    Note: This rule can be applied to any other third-party technology, such as Flash or Java. If it's not built into every web browser/device or if it can be disabled, then make sure the page is still accessible and usable without it.

  4. Do you avoid using "inherit" value of style.display?

    The property value “inherit” of style.display is not recognized by IE7 and IE7 compatibility mode. So if you use this value in Javascript, it will cause script error in IE7 and IE7 compatibility like: 
                "Message: Could not get the display property. Invalid argument."
    So to make your Javascript and CSS style more compatible and avoid using "inherit" value of style.display:
    divLoading.style.display = "inherit"; 
    Bad code - inherit property
    divLoading.style.display = "block"; 
    Good code - block property
  5. Do you avoid using document.getElementById(id) and document.all(id) to get a single element, instead use selector $(#id)?

    $(#id) is a selector of jQuery. It gets the single element with the given id.

    jQuery ​is a fast and concise JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.​

    ​With jQuery, you can write less code but do more work.

    <h1 id="Head1">Hello</h1> <script type="text/javascript" language="javascript">
    document.all("Head1")
    .style.color="red"; </script>

    Figure - Bad Code​​​

    <h1 id="Head1">Hello</h1> <script type="text/javascript" language="javascript">​​
    document.getElementById("Head1")
    .style.color="red"; </script>

    Figure: Bad Code​

    <h1 id="Head1">Hello</h1> <script type="text/javascript" language="javascript">
    $("#Head1")
    .css("color","red"); </script>

    Figure: Good Code - Using $("#Head1")​​​
  6. Do you comment your JavaScript code?

    Comments are used to add extra information pertaining to your code. They not only make you understand your code when you look at it after a period of time, but it also help other people who might be working with you on the same project.

    The goal is to write clear, concise and meaningful comments. They should describe your code in a way you or others understand what that particular piece of code does.

    In other words, let your code speak for itself.

    How to comment in JavaScript?

    • Single-line comments - begin with a double forward slash (//)
    • Multiline comments - start with slash-asterisk (/*) and end with asterisk-slash (*/) pair.

    Generally use line comments. Use multiline comments for formal documentation and for commenting out.

    Comments are ignored (not processed as coding) by the browser, however it makes you code heavier, so always try to keep your comments short by writing only what's needed to convey the idea.

    document.write ("Example!"); // prints a message

    Figure: Although this example sounds unnecessary for a developer, it shows clearly how comment should be kept simple and informative
  7. Do you encapsulate your scripts to avoid cluttering the global namespace and clashing with other scripts?Unpublished

    It's very common to see people creating variables and methods in the global namespace not worrying about how they will behave in conjunction with other libraries and custom codes. Once you have a handful of libraries and several people working on the same project you'll find that a lot of method and variable names will overlap, so if you don't take enough care, you will have your methods and variables overwritten and your page breaking for no apparent reason.

    var buttonClicked = false;
    function click()
    {
         buttonClicked = true;
    }​

    ​​​​​Bad example - create variables and methods in the global namespace 

    In order to avoid your variables and methods to be overwritten, it's best practice to encapsulate them.

    ​​(function(ssw){
        var buttonClicked = false; //private variable 
        ssw.click = function(){​ //public method
        {
            buttonClicked = true;
        }
    }(window.SSW = window.SSW || {}));

    ​Good example - the variable and method are now encapsulate and under a distinct namespace

    ​​By encapsulating your script using this anonymous function, you can as well pass some parameter to be used within it and again not worrying about being overwritten somewhere else.​ A very used library is jQuery, simply referred as $ in the code, although ​it's not common, in some cases you'll see the $ conflicting with some existing library and to avoid that we can pass jQuery as a parameter for this anonymous function then use $ freely inside that context.

    ​​(function(ssw,$){
        var buttonClicked = false; //private variable 
        ssw.click = function()​ //public method
        {
            buttonClicked = true;
            $('#id').html('<span>Example</span>');
        }
    }(window.SSW = window.SSW || {}, jQuery));

    ​​​Good example - jQuery being passed as parameter of the anonymous function

    ​​​Since JavaScript is very forgiving language, you could even redefine the meaning of undefined to something like true, which would probably make a lot of noise inside your code, to avoid this let's make sure that undefined is really undefined by completing this pattern this way:

    (function(ssw,$,undefined){
        var buttonClicked = false; //private variable 
        ssw.click = function()​ //public method
        {
            buttonClicked = true;
            $('#id').html('<span>Example</span>');
        }
    }(window.SSW = window.SSW || {}, jQuery));​ //nothing added as the third parameter

    ​​​Good example - making sure undefined is really undefined
  8. Do you know not to use the "eval" function?

    The Javascript command "eval" evaluates the content of a text string and then runs it as Javascript code. It's common to see it around, however "eval" is one of the most inefficient constructs that JavaScript has. There are always more efficient ways to code and get a direct reference.

    Most of people that use "eval" want part of a variable name to be variable.

    Once you realize that all global variables are held in the window array it becomes rather obvious that you can refer to that same field name without needing to use "eval" by referring to it.

    eval('somevar' + num)

    Figure: Bad example - The developer creates the variable name by concatenating the constant and variable parts together

    window['somevar' + num]

    Figure: Good example - Referencing the same field is as simple to code and more efficient than using "eval"
  9. Do you know the best tools to debug Javascript?

    ​Debugging JavaScript application can be difficult. Having to console.log results can make for a slow and cumbersome development experience. There are five ways you can debug a JavaScript application without leaning on console.log() as your main tool.​

    Options for Debugging JavaScript applications

    1. Debug your JavaScript using console.log()
      While this is a valid approach it should only be utilized for the simplest of manual debugging tests as they are slow, you have to re-run the app every time, do not allow you to change state mid-flight and developers sometimes forget to clean up after themselves and the code becomes riddled with console.log statements.

      debug-js-1.png
      Bad code - Using console.log() to debug your JavaScript

    2. Debug in the browser with a breakpoint
      Chrome is by far the most popular browser for the average web developer followed by FireFox, but all the major browsers have a debugging tool.
      debug-js-2.png
      Figure: Old school JavaScript debugging with Chrome Dev Tools is still the best and most versatile tool
    3. Debug in an IDE
      It is often more effort than it is worth to debug JavaScrtipt in your IDE and it is still not very popular. If your app is a Server Side NodeJS JavaScript app then it is very different since this type of JavaScript app does not run in the browser and this is what the IDE is designed for. 
      • Visual Studio Code Chome Debugger - Painful to set up source maps for advanced JavaScript applications that run in memory dev servers like WebPack Dev Server.
      • Visual Studio 2015 - Only works with TypeScript in Internet Explorer
      debug-js-3.png
      Figure: Visual Studio Chrome Debugger with breakpoint set
    4. Time Travel Debugging with Redux
      Using tools like ngrx's store dev tools . You can traverse back and forth between states with excellent UI tools. Debugging through your states is much better than just debugging the current state but also to be able to see the actions triggered to change state.
      debug-js-4.png
      Figure: Example of redux based time travel debugging
    5. Hot Module Reloading
      The problem with the above approaches is every time you make a change to your code you need to reload the website and navigate back to the page and state of that page again and again to repeat your manual test. Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running without a page reload.
      debug-js-5.png
      Figure: Hot module reloader documentation from WebPack website
  10. Do you know what are the best examples of technically cool jQuery plug-ins?

    Below are some of the best technically cool jQuery plug-ins. Use these as guidelines for building your jQuery plug-ins:

  11. Do you know what are the best examples of visually cool jQuery plug-ins?

    ​Below are some of the best visually cool jQuery plug-ins. Use these as guidelines for building your jQuery plug-ins:


  12. Do you know when to use TypeScript (vs JavaScript and CoffeeScript)?

    ​TypeScript is the new flagship language from Microsoft that compiles into JavasScript.

    • Use JavaScript if you’re writing page specific script
    • Use jQuery to improve cross-browser support
    • Use TypeScript if you’re writing re-usable client side library

    Don't use CoffeeScript (language is too different from JavaSript)

    Figure: Good - TypeScript is very similar to JavaScript so it’s easy to learn, and also helps developers learn proper JavaScript coding practices
    Figure: Bad – CoffeeScript syntax is very different from JavaScript so it takes longer to learn
  13. Do you know which version of jQuery to use?

    New jQuery versions are released regularly, but you shouldn't always use the latest version.

    ​If your site needs to support Internet Explorer 6, 7, and 8, you should not use the latest version of jQuery.  You should use the latest version 1.9.x instead.

    The jQuery authors made a decision to deprecate support for older versions of IE from version 2.0 onwards.  Even though support for these browsers has been discontinued, the authors have commited to maintaining version 1.9 so it's safe to keep using it.

    For more information about the changes, see the jQuery blog post about the version 2.0 release.

  14. Do you know you should not open popup windows and use a javascript modal instead?

    The popup blockers in several browsers prevent JavaScript from being used to open windows without user interaction (e.g. clicking a link). You should use an anchor tag instead.

    ​<body onload="window.open('http://www.mydomain.com/document.html');return true;">

    Figure: Bad Example - using JavaScrip in OnLoad event​

    ​<a href="http://www.mydomain.com/document.html" target="_new">Document</a>

    Figure: Good Example - Using HTML anchor tag. This will open in a new tab or window depending upon browser configuration​​

    <a href="#" onclick="window.open('http://www.mydomain.com/document.html');return false;">Document</a>

    Figure: Good Example - Using Javascript in an onclick event means you can force a popup window in preference to a new tab and also control the size and placement of the window

    We have a program called SSW Code Auditor to check for this rule.


  15. Do You Place Scripts at the Bottom of Your Page?

    Bear in mind that the load time is a very important aspect on web development. The goal is to make the page load as quickly as possible for the user.

    It's known that when a browser loads a script, it can’t continue on until the entire file has been loaded.

    Once JavaScript files have the purpose to add functionality — something happen after a button is clicked for example — there is no good reason to load the JS file before the button itself.

    So go ahead and place JS files at the bottom of the HTML, just before the closing body tag.

    <script type="text/javascript" src="file.js"></script>
    </body>
    </html>

    Figure: Place JavaScript at the bottom of your HTML

    Tests at a big online sales company revealed that every 100 ms increase in load time decreased sales by 1%.

  16. Do you remove "Language" from your script tag?

    A few years ago, it was common to have the "language" attribute within the script tags. This attribute was used to specify the scripting language of the contents of this element.

    Since these identifiers are not standard, this attribute has been deprecated in favor of "type".

    <script href="script.js" language="javascript"></script>

    Figure: Language attribute has been deprecated

    <script href="script.js" type="text/javascript"></script>

    Figure: The scripting language is specified as a content type

    Read more on W3C website.

  17. Do you separate JavaScript functionality (AKA Unobtrusive JavaScript)?

    A website can be broken down into three main development parts: content, design and functionality. To optimize a website for search engines, it's important to separate the content  (crucial for search engines) from design and functionality (not important for SEO).

    All JavaScript code should go into an external .js file (linked to the document with a <script> tag in the head of the page) and not embedded within HTML. The same should be done for CSS files. Don't bloat your HTML file and confuse search engines. Separate the legitimate content from what is programming code.

    <a onclick="action()" href="#">Click Here</a>

    Figure: Never include JavaScript as inline attributes

    <a href="backuplink.html" class="action">Click Here</a>

    Figure: JavaScript (included in an external file) should use a class or id for its behaviours
  18. Do you streamline your development process with NPM and Task Runners?

    ​The current trend in web development is to use a large range of front-end libraries to give a great user experience.

    However, .NET devs know it is no easy task to manage all of these on top of a large script folder. Previously we tried to improve and streamline the process by using NuGet, but found this package manager was ill-suited.


    Another issue was that due to the requirement of checking the library’s files into source control, this has the potential to grind fellow devs to a halt while Visual Studio tries to make sense of the myriad of small JavaScript files. Furthermore, there were many smaller tasks that needed to be completed, such as minification and bundling. In the older versions of Visual Studio, a large portion of these tasks had be performed manually by the developer.

    Needless to say, however a developer could try to tackle this task, it was always a challenging and time consuming endeavour.


    Enter Visual Studio 2015 with NPM (Node Package Manager) in-built. This package manager has been built from the ground up to make downloading your JavaScript libraries simple. These tools existed outside of the .NET space, but in 2015 they’ve been brought into the fold and made easy to use in Visual Studio 2015.

    With NPM, we specify the name of the package and the version number we want to use, and the tool does all of the hard work finding and downloading the library. Because NPM is run on each developer’s machine, libraries are no longer added to source control. Rather, they are quickly downloaded from the trusted NPM CDN.


    bower json.png 

    Figure: Example of NPM in action

    Working in tandem with NPM are task runners, which are JavaScript tools that can be used to add automation to your project by having them perform simple yet tedious tasks that are required to get your libraries ready for use, such as compilation, linting, and minification. Just use NPM to install the task runner of your choice, and away you go.

    There are a heap of different task runners out there, the two best known are Gulp and Grunt.

    gulp vs grunt.png 

    Figure: In short they both perform the same job but Gulp is faster and requires less configuration

    For example, we could previously use web essentials to do a lot of the necessary bundling and automation, but this was killed off at the start of 2015.

    removed features.png 

    Figure: The updated feature list for Web Essentials 2015

    This key feature was removed, but with the addition of tasks runners to Visual studio 2015 we can reimplement the functionality, by using ether Gulp or Grunt. For a number of reasons, Gulp is the better choice over Grunt: seen below is an example of a task for Gulp that will compile .less to .css



    var gulp = require('gulp');


    var less = require('gulp-less');


    var path = require('path');


    var plumber = require('gulp-plumber');


    gulp.task('less', function () {


     return gulp.src('./Content/**/*.less')


     .pipe(plumber())


       .pipe(less({


           paths: [path.join(__dirname, 'less', 'includes')]


       }))


       .pipe(gulp.dest('./content/'));


    Glup 101 in Visual Studio 2015​ ​​​​


  19. Do you treat JavaScript like a real language?

    JavaScript is a real language and should be treated like one!
    Would you put all your C# code in one file? Would you write single modules with every method your application could need?  Of course not!
    It's important to maintain coding standards when writing JavaScript just as you would when writing C#.

    Where appropriate, try to follow the Rules to Better Architecture and Code Review with your JavaScript as well.  In particular, make sure you're still following the SOLID principles as much as you can.
  20. Do you use Bundling and/or AMD

    ​​Minification and AMD are techniques to improve javascript performance. They can both can be used with vanilla JavaScript and with Typescript

    ​​​AMD and RequireJs

    AMD is a client-side technology​​​ that allows you to break you Js code into small inter-dependent modules. The modules (and thier dependencies) required to render a particular page are determined at runtime and subsequently downloaded by Javascript. RequireJs is a popular AMD implementation.

    Pro: Only the js modules you need are downloaded
    Con: Each module is downloaded in a separate http request

    ​Bundling and Minification

    ​This is a server side technique that combines and optimises client side files into single, optimised downloads.

    ASP.Net contains excellent server-side bundling support as outlined here: http://www.asp.net/mvc/overview/performance/bundling-and-minification​

    ASP.Net vnext & VS 2015 also provides support for using task runners like Gulp or Grunt for bundling and minification.​

    Pro: Fewer Http requests and smaller files
    Con: All client side modules are included in a single download​
  21. Do you use jQuery instead of JavaScript?

    jQuery is the MUST HAVE tool for web developers. There are 3 good reasons why you should use jQuery.

    1. Cross Browsers (IE 6.0+, Firefox 2+, Safari 3.0+, Opera 9.0+, Chrome)
    2. Powerful and easy to use
      • Same selectos as CSS
      • Designer can learn it fast
      • More readable JavaScript code
    3. Plug-ins - Tons of useful plug-ins and functionalities​

    ​window.onload = function() { alert("Welcome"); }

    Figure: Bad Example - Using JavaScript 'onload' event

    $(document).ready(function() { alert("Welcome!"); });

    Figure: Good Example - using jQuery document 'ready' event​
  22. Do you use lodash to perform your daily _.foreach?

    In a nutshell, Lo-Dash is a super useful library that gives you access to over 100 extremely performant functions to help you avoid reinventing the wheel whilst writing JavaScript.

    You can get lodash from GitHub repositorycdnjs or via NPM. Once done you can include a reference in your HTML.

    ​A simple example of the power of lodash is this snippet of code which is looping through a shared Kendo datasource that is being used in large Kendo grid. The shared datasource has many duplicates and this snippet does four things:

    1. Removes duplicate account numbers
    2. Plucks out only the account numbers into a new array
    3. Sorts the array by alphabetical order
    4. Removes blank entries

    This new simplified array of account numbers was then used in a dropdown to filter the Kendo grid. This single line saves a call to the database for another array of data and populates the dropdown with the same shared datasource. This would be a pain to write with vanilla javascript and difficult to read.

    this.accountNumberDropDownData = _.chain(this.sharedDataSource).pluck('AccountNumber').uniq().sortBy().value();

    Good example - Simple one line of TypeScript which would take many line of code without lodash

    If you have been into JavaScript development for a while you may of also heard about underscore.js which is very similar to Lo-Dash but has some fundamental differences.

    I created Lo-Dash to provide more consistent cross-environment iteration support for arrays, strings, objects, and arguments objects1. It has since become a superset of Underscore, providing more consistent API behavior, more features (like AMD support, deep clone, and deep merge), more thorough documentation and unit tests (tests which run in Node, Ringo, Rhino, Narwhal, PhantomJS, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with custom builds and template pre-compilation utilities.

    — John-David Dalton

    Further reading:

    1. https://lodash.com
    2. http://underscorejs.org
  23. Do you use the .ready() function?

    Putting your initialization JavaScript code inside the .ready function is not always required, but it's much safer to do so.

    ​jQuery exposes a .ready event which fires when the Document Object Model (DOM) is fully loaded and ready to be manipulated.

    You can attach a function to this event so you can be sure the page is ready for you to work on.

    $('#login').addClass('hidden');

    Figure: Bad Example - if this jQuery is in the wrong place, the #login element may not exist!

    $(function() {
        $('#login').addClass('hidden');
    });

    Figure: Good Example - this code won't run until the DOM is fully loaded

  24. Do you use the best JavaScript libraries?

    It's important to keep on top of what the best JavaScript frameworks are. 

    In this explosive video Ben Cull, SSW Solution Architect, will bombard you with what are the best JavaScript Frameworks to use in 2016.

     


  25. Do you use the best Web UI libraries?

    ​Don't waste time evaluating which Web UI libraries to use. Most of the commonly used libraries are very similar in functionality . The recommend  library is Twitter Bootstrap.

    It's the most popular available framework today, which means more people involved in the project, more tutorials and articles from the community, more real-world examples/websites, more third-party extensions, and better integration with other​ web development products

    zurb.png
    Figure: Bad example - Zurb Foundation is the second most popular, but it uses Sass files and​ has the worst name

    In VS 2013 Zurb Foundation was always out of date on Nuget. So if you use it (which is not recommended) download it direct from ​Github.​​ 

    In VS 2015 these packages were moved from N​uget to Bower. 

    bootstrap.png
    Figure: Good example - leader among frameworks today, Bootstrap toolkit is recommended to build​ successful websites

    The 3 things a developer need to know to get up and running quickly with ASP.NET MVC

     

    Twitter Bootstrap & ASP.NET MVC ​​​​- Intro / Quickstart

     

    ​Other useful frameworks​

    Now that you saved a lot of UI develo​pment time by using Bootstrap, you can play around with other useful frameworks.​

    • KendoUI for enhanced HTML and jQuery controls
    • KnockoutJS for view-model data binding
    • SignalR for real-time web functionality​