5 things you might be doing wrong in Javascript

1. Do not use console.log for debugging

This is the most common way of debugging and it’s effective but only for 1 page scripts. If you wish to create full fledged application console.log can rapidly become a headache to manage while debugging. You need an efficient way of debugging. You need a minimal framework to segregate the app context from each other. There are many libraries that do that like debug which is available in various frameworks like express itself. debug library is relatively small and have several cool features that can save you a lot of time while searching through the right messages.

2. Mixing async await with callback

This can easily happen to guys who used js pre async-await times and their application already has some thousands of callback functions. async-await do not gel well with callbacks. You have only two options.

Either change every callback in your application flow to async-await or don’t use it all

Mind you it is not easy to replace callback in old heavy libraries. You should do it when you are required to integrate new library which uses async await and yes, it will take time.

I am not saying it’s not possible. It is but it will make code more complex.

3. Not calling return after callback

The most common and notorious mistake. As a rule of thumb always return from functions right after callback.

The only time you would not want to do that is when you have some processing which do not depend on the callback. These calls should be refactored in a way where callback is the last function. Because, it should not matter where we call callback functions if it is independent from the rest of the code.

For eg, consider this function:

  function greeting(name) {   console.log('Hello ' + name); }
 function processUserInput(callback) {
   var name = prompt('Please enter your name.');
       callback(name); 
        console.log("I am not dependent on callback and can be called anywhere")
   } 
   processUserInput(greeting);

The above function has no issue but as the code grows, we can have some dependency involved. It can be rewritten as

function greeting(name) {   console.log('Hello ' + name); }
 function processUserInput(callback) {
   var name = prompt('Please enter your name.');
       console.log("I am not dependent on callback and can be called anywhere")
       callback(name); 
       return;
   } 
   processUserInput(greeting);

4. Using sync functions for APIs

5. Using too many arguments in a function call

Leave a Reply

%d bloggers like this: