7 minute read

Here it is, the long awaited 50+ useful JavaScript tips, tricks and best practices.

I originally wrote this for fun and to help me understand more about JavaScript as well as settle some common arguments that kept coming up in the community.

Having lived with JavaScript for a long time now, I thought it was high time that I decided that I should write up some of the JavaScript tips with references to help those starting out.

Here’s some tips and tricks to help you get to grips with JavaScript.

Enjoy!

50+ Useful JavaScript Tips, Tricks and Best Practices

  1. Event delegation allows you to attach an event listener to an element.
  2. Understand this and avoid that, use Function.prototype.bind instead.
  3. JavaScript is a prototype-based programming and requires an understanding of prototypical inheritance - instead of creating classes, you make prototype objects, and then use the object function to make new instances.
  4. JavaScript Module Systems, CommonJS (as used in Node.js modules) defines a module format and RequireJS implements the Asynchronous Module Definition. ES6 modules attempt to bring harmony between the two.
  5. Immediately-invoked function expressions (IFFE) - The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements.
  6. The difference between null - the intentional absence of any object value, undefined - assigned to variables that have just been declared and undeclared - undeclared variables do not exist until the code assigning to them is executed, and how to check for them.
  7. Closure functions and how they work in JavaScript - these functions allow you to execute within their own context, rather than the global scope.
  8. The difference between a forEach loop (iterates over an array) and a .map() loop (transposes arrays) and when to use them
  9. Anonymous functions and when to use them - For example, when attempting to sort in a non-standard way, it may be easier to contain the sorting logic as an anonymous function instead of creating a named function
  10. Software design and code organisational patterns such as the module pattern, classical inheritance, Model–view–presenter, Model–view–adapter, Model–view–viewmodel
  11. The three object categories in JavaScript: Native Objects, those provided by Javascript, Host Objects, such as the ones you get in environment like console, and User-Defined Objects, the ones you define
  12. Expressions versus statements - a statement performs an action (eg: loops and ifs), expressions produces a value (eg: as an argument in a function call) and function constructors
  13. The difference between .call and .apply, call counts the number of arguments separated by comma, while apply uses array as an argument
  14. Browser detection is bad, Feature detection is not browser detection, instead libraries such as Modernizr use feature detection
  15. Ajax is Asynchronous JavaScript And XML, its uses XMLHttpRequest to asynchronous retrieve data - there’s pros and cons, the main advantage is that it doesn’t require full page refreshes to load dynamic data into a page, which means less load on the client and server, that’s also it’s downside as if the client doesn’t support it, such as a search engine bot, you will not get all the content.
  16. JSONP is JSON with Padding, used to request data from a server residing in a different domain than the client, but has since seen replaced by CORS due to security concerns
  17. JavaScript templating and libraries such as AngularJS, Backbone.js, Ember.js, Handlebars.js, Vue.js and Mustache.js.
  18. Hoisting in JavaScript means that variable and function declarations are moved to the top of their containing scope.
  19. Event bubbling, where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the hierarchy till it reaches the top.
  20. The difference between an “attribute” - belonging to a HTML element and a “property” - belonging to an object.
  21. Don’t extend the built-in JavaScript objects, mainly because it can break things in an unexpected way, but know how it can be done.
  22. The difference between window load event - when all the resources have loaded and document DOMContentLoaded event is when the DOM is ready to interact with
  23. Comparison operators: Strict comparison (===) is only true if the operands are of the same type and the contents match, while the regular abstract comparison (==), just checks content.
  24. Same-origin policy: Due to the rise in AJAX and cross-domain requests this raised some security concerns, to mitigate this, the same-origin policy was introduced
  25. Ternary operator: In JavaScript, the conditional (ternary) operator is the only operator that takes three operands, often used as a shortcut for the if statement
  26. Strict mode: It means you’ll write better JavaScript, but it comes at a cost that it might not be compatible with all clients or run-times
  27. The modulo operation in JavaScript is called the Remainder (%) Arithmetic operator
  28. Don’t touch the global scope, in the same way you wouldn’t use global variables
  29. JavaScript load events tell you when a resource has finished loading, you could use DOMContentLoaded if you didn’t need all the images to be loaded
  30. Single page app: a web application or web site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server, making them SEO friendly is not trivial, you need to be able to cache and serve static content
  31. Promises: handling of the eventual completion (or failure) of an asynchronous operation, and its resulting value. Native Promises are relatively new in JavaScript and require an introduction.
  32. Avoid callback hell, Promises may help you to write more maintainable code, but consider that you might not need Promises
  33. TypeScript: a strict syntactical superset of JavaScript, and adds optional static typing to the language, developed and maintained by Microsoft, also used at Google, also see CoffeeScript, which aimed to close gaps in compatibility with JavaScript
  34. Debugging: Use debugger, Chrome DevTools, the Console, etc
  35. Immutable objects remain unchanged after their creation, such as the native type objects (eg: String). In JavaScript you can use Object.defineProperty to define an immutable property of an object.
  36. JavaScript is Synchronous: operations occur at the same time, asynchronous functions wait for the eventual completion of an operation
  37. Event loop: a programming construct that waits for and dispatches events or messages in a program. JavaScript has a concurrency model based on an “event loop”, setImmediate() or setTimeout() can be used to offload CPU-intensive tasks to the next event loop cycle
  38. Call stack: a stack data structure that stores information about the active subroutines of a computer program. The call stack is primarily used for function invocation (call). In JavaScript, since the call stack is single, function(s) execution, is done, one at a time, from top to bottom. It means the call stack is synchronous.
  39. Function expressions: Function expressions in JavaScript are not hoisted, unlike function declarations. You can’t use function expressions before you define them
  40. Declaring variables: const - Constant, immutable, let - declares a block scope local variable, var - declares a variable
  41. Function constructors: In ES6 (ES2015) if you try to call a class constructor without new, it will always throw an error.
  42. Arrow functions: An arrow function expression has a shorter syntax than a function expression and you no longer need to bind this. Arrow functions are best for callbacks or methods like map, reduce, or forEach.
  43. Higher-order functions: In JavaScript we call them “callbacks”, it’s a function that is passed to another function
  44. Destructuring assignments: a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables
  45. Template Literals: String literals that allow embedded expressions, allowing multi-line strings and string interpolation features
  46. Curry functions: a process to reduce functions of more than one argument to functions of one argument with the help of lambda calculus
  47. Spread syntax: allows an iterable (eg: array) to be expanded in places where zero or more arguments are expected, like in function calls. The remaining properties are assigned to the variable after the spread operator
  48. You can share code between files in Javascript, including Lerna, a tool for managing JavaScript projects with multiple packages
  49. Node.js: A runtime system that can be used to power your backend
  50. Use Linting: analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs. Use ESLint
  51. Use an IDE: a software application that provides comprehensive facilities to computer programmers for software development, such as VScode or Atom
  52. RTFM: The Mozilla Developer Network JavaScript Guide is pretty comprehensive, so it’s a good place to start.

Also see:

Comments