50+ Useful JavaScript Tips, Tricks and Best Practices
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!
- Event delegation allows you to attach an event listener to an element.
- Understand
this
and avoidthat
, useFunction.prototype.bind
instead. - 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.
- 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.
- 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.
- 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. - Closure functions and how they work in JavaScript - these functions allow you to execute within their own context, rather than the global scope.
- The difference between a forEach loop (iterates over an array) and a .map() loop (transposes arrays) and when to use them
- 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
- Software design and code organisational patterns such as the module pattern, classical inheritance, Model–view–presenter, Model–view–adapter, Model–view–viewmodel
- 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
- 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
- The difference between .call and .apply, call counts the number of arguments separated by comma, while apply uses array as an argument
- Browser detection is bad, Feature detection is not browser detection, instead libraries such as Modernizr use feature detection
- 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.
- 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
- JavaScript templating and libraries such as AngularJS, Backbone.js, Ember.js, Handlebars.js, Vue.js and Mustache.js.
- Hoisting in JavaScript means that variable and function declarations are moved to the top of their containing scope.
- 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.
- The difference between an “attribute” - belonging to a HTML element and a “property” - belonging to an object.
- 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.
- 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
- 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.
- 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
- 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 - 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
- The modulo operation in JavaScript is called the Remainder (%) Arithmetic operator
- Don’t touch the global scope, in the same way you wouldn’t use global variables
- 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
- 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
- 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.
- Avoid
callback
hell, Promises may help you to write more maintainable code, but consider that you might not need Promises - 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
- Debugging: Use debugger, Chrome DevTools, the Console, etc
- 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.
- JavaScript is Synchronous: operations occur at the same time, asynchronous functions wait for the eventual completion of an operation
- 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()
orsetTimeout()
can be used to offload CPU-intensive tasks to the next event loop cycle - 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.
- Function expressions: Function expressions in JavaScript are not hoisted, unlike function declarations. You can’t use function expressions before you define them
- Declaring variables:
const
- Constant, immutable,let
- declares a block scope local variable,var
- declares a variable - Function constructors: In ES6 (ES2015) if you try to call a class constructor without
new
, it will always throw an error. - 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. - Higher-order functions: In JavaScript we call them “callbacks”, it’s a function that is passed to another function
- Destructuring assignments: a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables
- Template Literals: String literals that allow embedded expressions, allowing multi-line strings and string interpolation features
- Curry functions: a process to reduce functions of more than one argument to functions of one argument with the help of lambda calculus
- 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
- You can share code between files in Javascript, including Lerna, a tool for managing JavaScript projects with multiple packages
- Node.js: A runtime system that can be used to power your backend
- Use Linting: analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs. Use ESLint
- Use an IDE: a software application that provides comprehensive facilities to computer programmers for software development, such as VScode or Atom
- RTFM: The Mozilla Developer Network JavaScript Guide is pretty comprehensive, so it’s a good place to start.
Also see:
Comments