How to debug logic errors in Javascript

Dung Do Tien Feb 12 2020 667

I just start researching javascript yesterday, I write a simple application to calculate some numbers, but it not correct. 

   <title>Title of the document</title>
    <h1>My first application</h1>
    <span id="lblResult"></span>
        var a = "10";
        var b = (a + 2) / 2;
        document.getElementById("lblResult").innerHTML = b;

I don't know why my result is 51 but not for 6.  Please explain and guide for me how to debug variables in javascript. I think if I can debug I can explain for myself. Thanks many!!!

Have 1 answer(s) found.
  • M

    Marry Christ Apr 03 2020

    I think you should be lean use Developer Tool in the browser. In some major browser is available Developer Tool for you (chrome, firefox, safari, opera, IE, Edge...). Developer Tool will help you debug javascript code, CSS and some thing more.

    1. Debug with chrome (recommend)

    You can follow by bellow link with step by step form Google chrome

    OR see video here


    2. FireFox

    See video and work follow


    3. Other browsers

    You can go to google search and type "how to debug js in Browser name" will have the answer for you.


    Back to your question "why the result is 51 but not for 6"

    Answer: a variable is a string and we have a rule string + number = string so "10"+ 2 = "102"

    => "102" / 2 = 51 

    Maybe you will question why string / number = number

    you should remember operator / and * only use for number and them auto convert string to number, so if the string is not a number you will get a value of NaN.

    Ex: "a" + 2 = "a2" but "a" / 2 = NaN.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close