How do you check your bugs in javascript code?

How do you check your bugs in javascript code?
0

#1

Hey,

I am working on Wikipedia article viewer. I got stuck but i don’t want to share the problem until i can’t find the solution myself. So, how do you check your javascript code? I know jshint.com, but it didn’t find me what’s particularly wrong with my code. When i execute my code through the JSHint, everything seems fine. I’m probably forgetting something with AJAX request : /

My codepen:

https://codepen.io/RycerzPegaza/pen/EyKjJX?editors=0010


#2

For everything vanilla (no libraries/framework) I always use REPL.it as a quick way to check my code.

For everything else, my Chrome developer tools tab is always open. That way you can quickly now if anything’s wrong.

Jshint will warn you about syntax but it won’t check if your code “works”


#3

I also have Chrome console opened (F12).
Right now I can see in your code two errors in console.

Also I usually put a console.log() statements in the places where I expect certain values to check them.

In you code I would start with:

  var value = "";
  $("#usr").keyup(function() {
    console.log('test'); // <-- this
    value += $(this).val();
    console.log(value); // <-- this
  });

And then I’ll look at the console and try to understand what is wrong.


#4

I console.log every line that I think may be the cause of the bug, I read the algorithms and try to make a map of the code that is executed and how it interacts with other lines of code.


#5

Pretty much. Some seems to be afraid of console.log but in some challenge I was litterally spamming the console to understand what worked or didn’t.


#6

I also recommend learning how to use Chrome’s debugger or Firefox’s Firebug debugger to use such things as breakpoints, watch-list, call stack, step-in, step-out, etc.

This is a good start Debugging JavaScript by Using Breakpoints. Those tools really allow you to drill down to problems buried deep in your code’s logic.

For simpler code, console.log is perfectly fine.

Tip: When using those debuggers above, try inserting debugger; where you suspect your code is failing and then run your code. It’s another way of inserting a breakpoint.


#7

Hey,

Why then when i try to console log the value of the variable called “value” i get this:

console.log(value);
VM1663:1 Uncaught ReferenceError: value is not defined(…)

I definetely have a variable which is defined. I defined it outsie the function as a string : var value = “”;


#8

I suspect it has something to do with codepen? I tried it on JSFiddle, and it’s logging the value fine.


#9

I don’t get this error about value, and in order to make your code work, you might replace this :

&callback=JSON_CALLBACK with &callback=?


#10

I changed it, these bugs don’t appear anymore. But i still fight with one more bug concerning cross domain requests - it seems like i don’t use jsonp, i guess?

This is what i get in the console when i click on the search button:

jquery.min.js:2 Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://codepen.io" from accessing a frame with origin "https://s.codepen.io". Protocols, domains, and ports must match.


#11

console.log(everything);

Seriously, if my code makes sense in my head but it isn’t giving me the results that I think it should, I will log everything to the console. I make sure that every console.log starts with text that indicates what it is.
console.log('userID before loop: ’ + userID);
console.log('userID in loop: ’ + userID);
console.log('userID after loop: ’ + userID);
Then I can trace how things change as they progress through my code and this will always let me spot where something doesn’t equal what I think it should.
From here, I usually have to go figure out why I can’t use a method the way that I thought I could because it doesn’t do what I thought it did.
Then I have to find a different way to accomplish my goal.


#12

I learned something new about console logging last night that suggests that it’s not always the predictable debugging tool we hope for. Read the Async Console portion of this chapter for some cases where console.log() behaves a little counter-intuitively: https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/ch1.md

This only relates to asynchronous JavaScript, but I’ve been caught out with some Async issues in my node microservices, so it’s worth being aware…


#13

I try to develop code locally then just copy past at the final stage. I still get sometimes cross domain security error if I am using Ajax requests even locally! It happened to me this morning! My way out was to install a local server, a simple one would do like the node http-server. when I finally transfer my code to Code Pen I found this article from Code Pen blog very helpful : https://blog.codepen.io/2013/09/23/ajax-codepen/ will help you more than two or three sentences of mine!

I hope my reply helps.


#14

Ok, You made it work on the local server, but how do you make it work on codepen so the error:

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&generator=searc…explaintext&exsentences=1&exlimit=max&callback=JSON_CALLBACK&gsrsearch=hey. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

doesn’t show up?

You see, I use $.getJSON with a callback, but i get this error in the console anyway.


#15

did you try?

    $.ajax({
      url: url + '&callback=?' , 
      dataType: 'jsonp',
      success: data => {
          console.log('success');
      }
    });

#18

Apart from console.loging (everything), you might want to benefit from a very simple assertion library such as chai - assert.

e.g. if you know a variable must be a string and must have a value of 'hello', simply write

// chai assert library
const assert = chai.assert;

let val = 'hell';
assert.isString(val, '"val" must be a string');
assert.strictEqual(val, 'hello', '"val" must have a value of "hello"');

then check your browser dev tools for any errors.
This is actually better than console.loging (in some aspects) because your devtool console won’t get flooded with unnecessary logs.

Also the mind blowing benefit is you just learnt how to write “tests”. You will be praised a lot in future for this practice. :slight_smile:

How to add to CodePen

  • Go to your pen
  • Click “Settings
  • Click “JavaScript
  • In the section “Add External JavaScript” section, type “chai” and add the library.

Check out http://codepen.io/abhisekp/pen/ezgLVg?editors=0010


#19

With some changes it worked :slight_smile:
I didn’t add ‘&callback=?’ to the url, because it was already there.

I don’t know why it didn’t work with $.getJSON unfortunately.

   $.ajax({
          url: mainLink,
          type: "GET",
          dataType: "jsonp",
          success: function (data) {
      console.log(data); 
// and other stuff i do with the data i get 
  }, 
          xhrFields: {
        withCredentials: false
      } 
        }) // end ajax

#20

it worked with &callback=JSON_CALLBACK. But i didn’t manage to make it work with $.getJSON, $.ajax worked. :slight_smile:


#21

You might benefit from using Postman for all your API call needs. :smiley:

Enjoy!


#22

I personally keep an eye for console log errors, add some to check values as I need and as @abhisekpsaid, I use postman when building APIs.