DEV Community

vivek
vivek

Posted on • Originally published at notanothervivek.com

DEBUGGING IN JAVASCRIPT - without fancy tools (for beginners or codeNewbies)

DEBUGGING IN JAVASCRIPT - without fancy tools (for beginners/codeNewbies)
Debugging can often be one of the most frustrating parts of programming. But, it can also be the part that teaches you the most about your code , and the programming language.

There are lots of dedicated tools & libraries for debugging, but often they can seem overwhelming, especially when you're a beginner. So, instead let's look at some reallyyyy basic ways to debug your javascript .

The main trick is to...wait for it.. use console.log() and comments for everything.

I can already feel a grave being dug for my web developer credentials due to this suggestion 😁

grave being dug

But, i believe in the power of "Keeping Things Simple", especially while learning. So, i'm taking the risk of suggesting some absolutely basic steps in this post .


How and Where to use console.log()

As you probably already know, console.log() helps to display the variables and info that you pass to it. Console also has many other useful functions, but,for the sake of absolute simplicity, we'll restrict ourselves to just console.log()

using console.log() with a comma and not a +

Most often, we see console.log() being used with string concatenation style, or without any description.

console.log(weird_cat_names)

console.log('value'+list_of_cringe_memories)
Enter fullscreen mode Exit fullscreen mode

These 2 approaches are certainly valid, but they may cause errors when the data type is not a string. For example, if you wanted to console.log() a json response from some API, the above approach might show errors.

One way to avoid such an issue is to use a , before the variable.

console.log('the api response = ',response_variable);
Enter fullscreen mode Exit fullscreen mode

This makes the browser parse the variable aptly and provides much more information about the variable, which can ease the debugging process.

being descriptive

Just randomly passing variables to console.log() could end up making your code seem even more confusing, since you may get a lot of outputs but not know where it happened.

To prevent this, try being really specific and add the name of the function, or what you are expecting to see in that line of code,etc.

console.log('response value inside for loop, in make_money() function = ',response_variable);
Enter fullscreen mode Exit fullscreen mode

It can also help you get a better idea of the flow of your code. Since you may also be using some asynchronous functions in javascript (which can be really frustrating at the start) being able to see the order of functions being executed can help you detect issues faster (especially related to the functions being called in an order that you did not expect).

grave being dug

(FYI - i've written a blog post about promises and async-await functions of javascript, that's aimed at absolute beginners and explained in non-technical terms : Without any codes , let's Understand PROMISES and ASYNC functions in Nodejs / Javascript (for beginners) . Hope you'll check it out as well )


adding console.log() at all major steps

  • as soon as a function starts, to know if it has received all the right input parameters
  • before ending a function, to know if the function has processed things according to your plan and given the right output
  • inside event listeners, to see if a particular event has been triggered or not
  • after any manipulation of data ; like concatenating strings, adding numbers, parsing json, stringifying json/data , etc.
  • when you get information from a 3rd party API or datbase

some common types of errors to look out for

  • parsing errors : mostly due to a function expecting a specific charset or data type).
  • incorrect syntax : minor differences like typos or extra spaces can often be the only error in your code. It may seem like such errors may be highlighted by the IDE, but there may also be instances where the typo version is frustratingly similar to some other valid function/class/object, which makes the IDE ignore it as an error.
  • variables being undefined : variables that are not initialized or ones that are out of the present scope, may be undefined and cause your script to malfunction.
  • functions being replaced : while using plugins in your IDE, sometimes your functions may be replaced unintentionally by some other very similar function or class.
  • memory leaks : sometimes when a function or data type is given a lot of data without being cleared efficiently, it can slowly add up and create issues. This is often rare unless you are handling large objects or processing binary data. So i would recommenr to not go about prematurely optimizing, unless it really seems to be a viable issue in your use-case.
  • infinite loops : an improperly used iterator, like for or while, can often make everything stuck, since it doesn't have a satisfactory/finite stop condition. console.log() inside such iterators can help you easily detect if such an issue is there in your code .
  • function not getting triggered : event listeners or 3rd party library functions may sometimes not be working, because they were not actually triggered by your code.
  • permission errors : while trying to get information from 3rd party sites, or even your own server, there may be permission errors that block the request, for security reasons.
  • version mismatch : different versions of libraries probably have minor changes that can cause conflicts with previously working codes. Using a different version can often solve some issues.

commenting, instead of deleting code

One way to find the exact spot that may be causing an error, is to comment out most of the code and then run the script after uncommenting in small batches. This can give you an understanding of what parts are working well, and identify the exact function or line which seems to be messing things up.

Often we'll need to keep trying multiple options to get one function to work. Instead of deleting and re-writing things often, it can be helpful if we just comment out our trials that didn't work. Then you can delete them later on. This can help you keep track of the approaches that you've already tried, and also prevent accidentally deleting a line that was already working.


Bonus Tip

const taco_type = ["soggy", "crunchy", "spicy"];
for (const the_choice of taco_type) { 
    console.log(the_choice); 
}
//when drunk & clueless, refer -> https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
Enter fullscreen mode Exit fullscreen mode

In your learning phase, try to add comments with the specific link that helped you sort out some issue. This can not act as a life-saving reference when you look at some parts of your code after a few days and wonder what in the world you did. [Beleive me, i've been there more times than i can honorably admit]

grave being dug


giving headlines to blocks of code

Adding extra comments to your codes can help in making your code less chaotic.

// START OF HACKING HASHNODE
function start_hacking(is_movie){
   while(is_movie === true ){
            tippity_tappity();
            i_am_in();
     }//while..is_movie ..true
}//start hacking

function tippity_tappity(){

}//tippity_tappity()


function i_am_in(){
let do = "put on sunglasses";
console.log(do); 
}//i'm in

//END OF HACKING HASHNODE

Enter fullscreen mode Exit fullscreen mode

Giving headlines to different sections can help you to identify which section you are looking at. Adding comments to the ends of functions and } in general, can help to keep track of where functions or iterators end, and prevent accidentally deleting them or adding extra code in the wrong place.


Confession

grave being dug

Before i end the post, i'll be the first to point out that all this info is probably a stone-age type approach to debugging,and some may be very captain obvious type info as well. But, i'm hoping that if it helps atleast one newbie developer,then it's worth writing the post.


THAT'S ALL DEV FAM 😃

Thanks again for taking out the time to read my post.

Hope you'll follow me on Twitter so that we can get to know each other, and grow together. Please feel free to DM me if you need any help with HTML,CSS,JS,NodeJS,MySQL,MongoDB or Redis while learning them.

Wishing good things for you always.

Top comments (0)