How to debug logic errors in Javascript

Dung Do Tien Feb 12 2020 118

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

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

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.
  • 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

    https://developers.google.com/web/tools/chrome-devtools/javascript

    OR see video here

    https://www.youtube.com/watch?v=H0XScE08hy8

     

    2. FireFox

    See video and work follow

    https://developer.mozilla.org/en-US/docs/Tools/Debugger

     

    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.

    Marry Christ Apr 03 2020
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